import java.io.File; import java.io.IOException; public class CreateFileExample { public static void main(String[] args) { try { File file = new File("test.txt"); if (file.createNewFile()) { System.out.println("文件创建成功!"); } else { System.out.println("文件已存在!"); } } catch (IOException e) { e.printStackTrace(); } } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFileExample { public static void main(String[] args) { try { File file = new File("test.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteFileExample { public static void main(String[] args) { try { File file = new File("test.txt"); FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("Hello, World!"); bufferedWriter.close(); System.out.println("写入文件成功!"); } catch (IOException e) { e.printStackTrace(); } } }
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com