private String read(String srcFile) throws Exception { //FileNotFoundException
Scanner in = new Scanner(new File(srcFile));
String result = "";
while (in.hasNextLine()) {
result += in.nextLine() + "\r\n";
}
in.close();
return result;
}
这段代码无法在远程服务器上读取文件内容,导致写文件都是 0 KB
这段程序可以在远程服务器上读写文件成功,但是写文件的时候,不能使用utf-8 编码,导致文件乱码。本地测试都没问题
try {
// read file content from file
StringBuffer sb= new StringBuffer("");
FileReader reader = new FileReader(srcFile);
BufferedReader br = new BufferedReader(reader);
String str = null;
while((str = br.readLine()) != null) {
sb.append(str+"\r\n");
//System.out.println(str);
}
br.close();
reader.close();
// write string to file
FileWriter writer = new FileWriter(toFile);
BufferedWriter bw = new BufferedWriter(writer);
bw.write(sb.toString());
bw.close();
writer.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
private void write(String result, String toFile) throws Exception {
Writer w = new FileWriter(new File(toFile));
w.write(result);
w.flush();
w.close();
}