记录一些典型的Java代码。
一、文件读取
1 public class Test4 {
2 public static void main(String[] args) {
3 try {
4 FileReader fdFileReader=new FileReader("bitch.txt");
5 BufferedReader bReader=new BufferedReader(fdFileReader);
6 String my=bReader.readLine();
7 while (my!=null) {
8 System.out.println(my);
9 my=bReader.readLine();
10 }
11 bReader.close();
12 } catch (IOException e) {
13 // TODO: handle exception
14 System.out.println("找不到指定文件");
15 }
16 }
17 }
二、文件写入
1 public class Test
2 {
3 public static void main(String[] args)
4 {
5 try {
6 String content = "Thank you for your fish.";
7
8 File file = new File("new.txt");
9
10 // create the file if doesn‘t exists
11 if (!file.exists()) {
12 file.createNewFile();
13 }
14
15 FileWriter fw = new FileWriter(file.getAbsoluteFile());
16 BufferedWriter bw = new BufferedWriter(fw);
17 bw.write(content);
18 bw.close();
19
20 }
21 catch(IOException e) {
22 System.out.println("IO Problem");
23 }
24 }
25 }
时间: 2024-11-07 10:20:26