Java对文件读写操作算是常用的操作,使用JavaIO较多,JavaIO提供的方式也很多,包括字节流、字符流。
本文使用缓冲字符流BufferedReader和BufferedWriter进行文件的读写。
1.读
//读文件
public String read(String fileName){
File file = new File(filename);
if(null != file && file.exists() && file.length() != 0L){
try{
String encoding = "utf-8";
InputStreamReader isr = new InputStreamReader(new FileInputStream(file),encoding);
BufferedReader bfr = new BufferedREader(isr);
String txt = bfr.readLine();
String context = "";
while(txt != null){
context = context + txt;
txt = bfr.readLine();
}
bfr.close();
return context;
}catch(IOException e){
e.printStackTrace();
}
return "error!";
}
2.写
//写文件
public Boolean write(String filename, String txt){
try{
//文件内容全替换
BufferedWriter bfw = new BufferedWriter(new FileWriter(filename));
//文件内容末尾追加
BufferedWriter bfw = new BufferedWriter(new FileWriter(filename,true));
bfw.write(txt);
bfw.flush();
bfw.close();
return true;
}catch(IOException e){
e.printStackTrace();
}
return false;
}
3.文件上传及下载
还可以通过SCPClient进行文件的上传和下载
Connection conn = new Connection("127.0.0.1");//使用服务器IP
try{
conn.connect();
conn.authenticateWithPassword("user","password");
SCPClient sc = new SCPClient(conn);
//下载至本地d盘
sc/get("/home/test.txt","d/");
//上传本地d盘文件至服务器
sc.put("d:/test2.txt","/home/");
}catch(IOException){
e.printStackTrace();
}
较为高级的操作是通过HttpServletRequest和HttpServletResponse进行文件的上传下载操作。
4642

被折叠的 条评论
为什么被折叠?



