文件的写入读取有很多方法,今天学到的是Scanner和PrintWriter
文件读取
Scanner in = new Scanner(Paths.get("file.txt"))
文件写入
PrintWriter out = new PrintWriter("file.txt")
- 文件读取的我目前只发现他是一行一行的读取不能整篇幅的读取,所以写了一个while循环,一行行的打印。
- 文件写入,写入的文件不能实现追加模式的写入。会把之前内容覆盖掉。
- 文件操作完,记得进行close()。
//Scanner文本文件读取与处理
package testbotoo;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.Scanner;
public class file {
public static void main(String[] arg) throws IOException{
//文件读取
Scanner in = new Scanner(Paths.get("C:\Users\...\Desktop\myfile.txt")); //读取文件操作
while(in.hasNextLine()){
String str = in.nextLine();
if(str.equals("9999")){
break;
};
System.out.println(str);
}
in.close();
//文件写入
PrintWriter out = new PrintWriter("C:\Users\...\Desktop\myfile.txt");
out.println("ssss");
out.println("5466555");
out.close();
}
}
由于不能写追加写入,又找到了一种新的解决办法:
import java.util.*;
import java.io.*;
public class T {
public static void main(String[] args) {
String fileName = "data.txt";
FileWriter fw = null;
PrintWriter toFile = null;
try {
fw = new FileWriter(fileName, true); // throw IOException
toFile = new PrintWriter(fw); // throw FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("PrintWriter error opening the file " + fileName);
System.exit(0);
} catch (IOException e) {
System.out.println("FileWriter error opening the file " + fileName);
System.exit(0);
}
System.out.println("Enter four lines of text:");
Scanner keyboard = new Scanner(System.in);
for (int count = 1; count <= 4; count++) {
String line = keyboard.nextLine();
toFile.println(count + " " + line);
}
System.out.println("Four lines were written to " + fileName);
toFile.close();
}
}