Java读取远程文件

在java中,读写远程机器上的文件可以通过IO类,URL类来实现,其中URL支持的协议有: http,https,ftp,mailto,file,gopher,jar,doc,netdoc,systemresource,verbatim等。

 以ftp为例子,具体实现如下

import java.net.*;
import java.io.*;
import java.util.*;
public class ReadURLFile{
 public static void main(String[] args) throwsException{
  URL urlfile = new URL("ftp://user:[email protected]/aaa.txt");
  BufferedReader in = newBufferedReader(new InputStreamReader(urlfile.openStream()));
  String content="";
  String inputLine =in.readLine();
  while(inputLine!=null){
   content +=inputLine;
   inputLine =in.readLine();
  }
  System.out.println(content);
  in.close();
 }
}//读文件;

 

import java.net.*;
import java.io.*;
import java.util.*;
public class WriteURLFile{
 public static void main(String[] args) throwsException{
  URL urlfile = newURL("ftp://wangxl:[email protected]/aaa.txt");
  BufferedWriter out = newBufferedWriter(newOutputStreamWriter(urlfile.openConnection().getOutputStream()));
  //String content="";
  //String inputLine =in.readLine();
  //while(inputLine!=null){
  // content +=inputLine;
  // inputLine =in.readLine();
  //}
  //System.out.println(content);
  out.write("fff and soon",0,5);
  out.close();
 }
}//写文件


你可能感兴趣的:(Java读取远程文件)