Java读写文件方法总结(推荐)
Java是一个非常强大的编程语言,用于读写文件时也同样灵活方便。下面是基于Java读写文件的方法总结。
读取文件
1. 使用InputStreamReader类
以下是使用InputStreamReader类读取文件的方法:
public static void readWithInputStreamReader(String fileName) throws IOException {
File file = new File(fileName);
InputStream inputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
2. 使用Scanner类
以下是使用Scanner类读取文件的方法:
public static void readWithScanner(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
写入文件
1. 使用PrintWriter类
以下是使用PrintWriter类写入文件的方法:
public static void writeWithPrintWriter(String fileName, String content) throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(content);
printWriter.close();
}
2. 使用FileOutputStream类
以下是使用FileOutputStream类写入文件的方法:
public static void writeWithFileOutputStream(String fileName, String content) throws IOException {
File file = new File(fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] bytes = content.getBytes();
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
}
以下是使用这些方法读取文件和写入文件的示例:
public static void main(String[] args) throws IOException {
// 读取文件示例
readWithInputStreamReader("src/main/resources/test.txt");
readWithScanner("src/main/resources/test.txt");
// 写入文件示例
String content = "Hello World!";
writeWithPrintWriter("src/main/resources/output1.txt", content);
writeWithFileOutputStream("src/main/resources/output2.txt", content);
}
使用这些方法读取和写入文件时,请确保文件的访问权限和路径。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java读写文件方法总结(推荐) - Python技术站