`
答案在风中
  • 浏览: 64115 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

关于文件传输

阅读更多

最近项目经常使用到文件传输ftp、url访问等方式,查阅了些资料做了些整理和添加并不完善,希望能对大家有所帮助。
1.ftp文件传输源码:
1.1采用Runtime.getRuntime().exec()执行操作系统的ftp命令
1.1.1 ftp上传脚本
Windows脚本:
open 目标IP
用户名
密码(没有密码则不用写)
cd 目标路径
asc
prompt
put 本地文件(完整路径)
bye

Unix脚本:
ftp -n -i 目标IP <<!EOF
user 用户名 密码
cd 目标路径
lcd 本地文件路径
asc
prompt
put 本地文件
bye
!EOF
  
这里传送的是文本文件,所以采用asc模式传输。然后Java Runtime执行命令 [Runtime.getRuntime().exec(cmd)] 如下:

1.1.2cmd指令
Windows命令:
ftp -s:脚本文件(完整路径)

Unix命令:
sh 脚本文件(完整路径)

1.1.3代码示例:(注意命令不要有空格)

a.脚本示例:C:/Users/gkq/Desktop/ftp.txt
open 127.0.0.1
gkq
cd gkq
asc
prompt
put C:/Users/gkq/Desktop/test1.txt
bye
b.代码:

public class RuntimeTest {
public static void main(String[] args) throws IOException{
@SuppressWarnings("unused")
java.lang.Process process = java.lang.Runtime.getRuntime().exec("ftp -s:C:/Users/gkq/Desktop/ftp.txt ");
}
}

 
注:貌似采用这种方式中文路径问题是无法上传的
1.2实现本地文件传输到ftp服务器指定目录(中文路径支持),需要使用apache common.net jar包
代码示例:

public class FtpClient{
private String userName;
private String pwd;
private String url;
private int port;
private FTPClient ftpClient;
public FtpClient(String url, int port, String username, String password) throws Exception {
this.url = new String(url);
this.port = port;
this.userName = new String(username);
this.pwd = new String(password);
ftpClient=new FTPClient();
}
private void connect() throws SocketException, IOException{
ftpClient.connect(url, port);//连接FTP服务器
FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);  
config.setServerLanguageCode("zh");  
config.setServerTimeZoneId("XXXX");
ftpClient.configure(config);
//设置默认超时
ftpClient.setDefaultTimeout(30000);
//设置数据超时
ftpClient.setDataTimeout(30000);
//socket超时
ftpClient.setSoTimeout(30000);
ftpClient.setBufferSize(524288);
//传输模式和类型
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);  
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
}
private void disconnect() throws IOException{
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
System.out.println("断开连接出错");
ioe.printStackTrace();
throw ioe;
}
}
}
private void login() throws Exception{
int reply;
try{
if(!ftpClient.login(userName, pwd)){
System.out.println("登入失败,用户名密码不匹配");
throw new Exception("登入失败,用户名密码不匹配");
}else{
//服务器是否响应
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new Exception("服务器无响应,登入失败");
}
}
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
private void logout() throws Exception{
try{
if(!ftpClient.logout()){
System.out.println("退出失败");
throw new Exception("退出失败");
}
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
public boolean uploadFile(String pathInPlatform, String filenameInPlatform, String fileInLocal) throws Exception{
try{
//连接ftp
this.connect();
//登入
this.login();
//转到指定目录,中文路径的处理
if(!ftpClient.changeWorkingDirectory(new String(pathInPlatform.getBytes("GBK"), "iso-8859-1"))){
System.out.println("访问目录不存在");
throw new Exception("访问目录不存在");
}else{
//上传文件
FileInputStream input=new FileInputStream(new File(fileInLocal));
ftpClient.storeFile(new String(filenameInPlatform.getBytes("GBK"), "iso-8859-1"),input);
input.close();
}
this.logout();
this.disconnect();
return true;
}catch(Exception e){
e.printStackTrace();
this.disconnect();
throw e;
}
}
}


2..web文件传输
通过url下载文件转为2进制流

public static synchronized byte[] getDataFromPlatform(URL url) throws Exception{
InputStream is=null;
HttpURLConnection httpConn;
int responseCode;
try{
    httpConn=(HttpURLConnection) url.openConnection();
responseCode=httpConn.getResponseCode();
if(responseCode==HttpURLConnection.HTTP_OK){
is=httpConn.getInputStream();
if (is != null) {  
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
byte[] buf = new byte[1024];  
int ch = -1;  
int count = 0;  
while ((ch = is.read(buf)) != -1) {//读取1024字节数据,存储到buf中  ,是否读完
baos.write(buf, 0, ch);//从0开始ch长度的byte写入outstream
count += ch;//总数   
}
is.close();
baos.close();
return  baos.toByteArray();//--->存到数据库中
}
else{
    throw new Exception("Error,input Stream is null");
}
    }else{
    throw new Exception("Connect error,can not get any data");
    }
    }catch(Exception e){
    e.printStackTrace();
    throw e;
    }finally{
    httpConn.disconnect();
    }
}

 

3.Socket传输
待整理….

 

分享到:
评论
2 楼 答案在风中 2013-05-06  
jay61439476 写道
//设置默认超时
ftpClient.setDefaultTimeout(30000);
//设置数据超时
ftpClient.setDataTimeout(30000);
//socket超时
ftpClient.setSoTimeout(30000);


请教下这几种超时分别是什么含义?

这个写的有段时间了,java doc上解释是这样
setDefaultTimeout(int timeout):Set the default timeout in milliseconds to use when opening a socket.默认的socket连接超时时间。
setDataTimeout(int timeout):Sets the timeout in milliseconds to use when reading from the data connection.数据读取超时时间,openDataConnection这个值会覆盖socketTimeout的值。
setSoTimeout(int timeout):Set the timeout in milliseconds of a currently open connection.Only call this method after a connection has been opened设置当前连接超时时间。
我代码里给的值设定应该是有冗余的,这个情景下setDataTimeout应该就够用。
1 楼 jay61439476 2013-05-06  
//设置默认超时
ftpClient.setDefaultTimeout(30000);
//设置数据超时
ftpClient.setDataTimeout(30000);
//socket超时
ftpClient.setSoTimeout(30000);


请教下这几种超时分别是什么含义?

相关推荐

Global site tag (gtag.js) - Google Analytics