用xftp设置成utf8格式上传后再读取文件会文件名乱码

时间:2023-01-05 08:51:37
 
 
 
    
	最近一直在做从ftp上读取文件并且下载文件,但是会出现乱码,一开始在获取文件名后转码的,发现虽然不乱码了但是文件却变成文件夹了后来才发现必须在连接ftp的时候就要设置编码格式
	
	
	public static void main(String[] args) {
    	FtpUtil util = new FtpUtil();
    	FtpInfo ftp = new FtpInfo();
    	ftp.setIp("******");
    	ftp.setPort("******");
    	ftp.setUserName("******");
    	ftp.setPassword("******");
    	try {
			util.connectServer(ftp, "");
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	try {
			util.getFileList("/");
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	try {
			InputStream is = util.downFile("/test.txt");
			
			util.readStream(is,"test.txt");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	
	}
	
	根据文件路径访问文件
	   public InputStream downFile(String sourceFileName) throws IOException {
    	ftpClient.enterLocalPassiveMode();
		//设置编码格式
    	return ftpClient.retrieveFileStream(new String(sourceFileName.getBytes("UTF-8"), "ISO-8859-1"));
//        return ftpClient.retrieveFileStream(sourceFileName);
    }
	
	
	//读取流
	   public void  readStream(InputStream inStream,String name) throws Exception {  
    	OutputStream  outputStream = new FileOutputStream(name);
        byte[] buffer = new byte[1024];  
        int len = -1;  
        while ((len = inStream.read(buffer)) != -1) {  
        	outputStream.write(buffer, 0, len);  
        }  
        outputStream.close();  
        inStream.close();  
        outputStream.flush();
    }