file和filehelper类小封装

  • 对文件写入写出的小封装File类和FileHelper

    File类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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实测

  • res文件夹在项目的根目录下
1
2
3
4
5
6
7
8
9
10
11
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类

1
2
3
4
5
public class FileHelper {
public static void copy(File file1, File file2) throws IOException {
file2.writeString(file1.readToString());
}
}

Main实测

1
FileHelper.copy(file1,file2);