- 对文件写入写出的小封装File类和FileHelper类
File类
import java.io.*;
public class File{
private String path;
public File(String path) {
this.path = path;
}
public String readToString() throws IOException {
FileInputStream input = new FileInputStream(path);
InputStreamReader reader = new InputStreamReader(input,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
String context = "";
String line = null;
while ((line = bufferedReader.readLine()) != null) {
context += line + "\n";
}
bufferedReader.close();
reader.close();
input.close();
return context;
}
public void writeString(String content) throws IOException{
FileOutputStream output = new FileOutputStream(path);
OutputStreamWriter writer = new OutputStreamWriter(output,"UTF-8");
PrintWriter printer = new PrintWriter(writer);
printer.print(content);
printer.close();
writer.close();
output.close();
}
}
Main实测
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File file1 = new File ("res/in.txt");
File file2 = new File ("res/out.txt");
String content = file1.readToString();
file2.writeString(content);
}
}
FileHelper类
public class FileHelper {
public static void copy(File file1, File file2) throws IOException {
file2.writeString(file1.readToString());
}
}
Main实测
FileHelper.copy(file1,file2);
网友评论