Java 学习笔记 - 读写字符文件

Posted 笑虾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 学习笔记 - 读写字符文件相关的知识,希望对你有一定的参考价值。

Java 学习笔记 - 字符流读写文件

读字符

FileReader 逐字读取

try (FileReader fileReader = new FileReader("E:\\\\in.txt");
     StringWriter stringWriter = new StringWriter();) 
    stringWriter.write('\\n');
    stringWriter.write("StringWriter输出:");
    
    int c;
    System.out.print("逐字输出:");
    while((c = fileReader.read()) != -1) 
        System.out.print((char)c);
        stringWriter.write(c);
    
    System.out.println(stringWriter.toString());
 catch (IOException e) 
    e.printStackTrace();

逐字输出:天使只是别处的凡人,神仙不过他山的妖怪。
StringWriter输出:天使只是别处的凡人,神仙不过他山的妖怪。

BufferedReader 逐行读取

StringBuilder sb = new StringBuilder();
String line;
try (FileReader fileReader = new FileReader("E:\\\\in.txt");
     BufferedReader br = new BufferedReader(fileReader);)

    while ((line = br.readLine()) != null)  
        System.out.println(line); // 逐行输出
        sb.append(line).append("\\n");  // 拼接字符串
    
    System.out.println(sb.toString());
 catch (IOException e) 
    e.printStackTrace();

Scanner 逐行读取

try(Scanner sc = new Scanner(new File("E:\\\\in.txt"))) 
    ArrayList<String> list = new ArrayList<>();
    while (sc.hasNext()) 
        list.add(sc.next());
    
    list.forEach(System.out::println);
 catch (FileNotFoundException e) 
    e.printStackTrace();

FileInputStream 读 UTF-8 字符集

字节流读取数据后以UTF-8方式解码字符串。

try (FileInputStream fis = new FileInputStream(new File("E:\\\\in.txt"));
     InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
     BufferedReader inbr = new BufferedReader(isr)) 
    String str;
    while ((str = inbr.readLine()) != null) 
        System.out.println(str);
    
 catch (Exception e) 
    System.out.println(e.getMessage());

Java7- Files:读取整个文件到 byte[]

读小文件很方便。

try 
    byte[] bytes = Files.readAllBytes(Paths.get("E:\\\\in.txt"));
    String str = new String(bytes);
    System.out.println(str);
 catch (IOException e) 
    e.printStackTrace();

java.nio.file.Files 下还有很多其他读取文件的方法如:
public static List<String> readAllLines(Path path, Charset cs)
public static List<String> readAllLines(Path path)

List<String> list = Files.readAllLines(path);
list.forEach(System.out::println);

Java8 - Stream 读取

逐行读取

  • 逐行输出
try (Stream<String> stream = Files.lines(Paths.get("E:\\\\in.txt"), StandardCharsets.UTF_8))
    stream.forEach(System.out::println);
 catch (IOException e) 
    e.printStackTrace();

Stream<String>String

String str = stream.collect(Collectors.joining("\\n"));

取第 N 行

通过流处理大文件,跳过N行,直接从目标行开始处理。

String str = stream
        .skip(10) // 跳过10行,取第11行
        .findFirst()
        .get();

Java8:BufferedReader

Java8 添加了 public Stream<String> lines() 可以获得流、 Files.newBufferedReader 可以获得 BufferedReader。配合使用就:

BufferedReader br = Files.newBufferedReader(Paths.get("E:\\\\in.txt"));
Stream<String> lines = br.lines();

Java11:读取整个文件

  1. 如果出错,会自动关闭文件。
  2. 如果文件大于2GB会报 OutOfMemoryError
Path path = Path.of("E:\\\\in.txt");
String str= Files.readString(path);

FileInputStream

写字符(新建)

写到临时文件

  • BufferedWriter、FileWriter 版
File tempFile = File.createTempFile("jerryTemp_", ".txt");
try(FileWriter fw = new FileWriter(tempFile);
    BufferedWriter bw = new BufferedWriter(fw);)

    bw.write("天使只是别处的凡人,神仙不过他山的妖怪。笑虾如是说。");
 catch (IOException e) 
    e.printStackTrace();

  • Files 版
final Path path = Files.createTempFile("jerryTemp_", ".txt");
try 
    byte[] buf = "那唐僧内眼凡胎不识妖怪,反护着它……".getBytes();
    Files.write(path, buf);
 catch (IOException e) 
    e.printStackTrace();

String s = path.toString();

FileWriter

FileWriter.write(String str, int off, int len) 字符串的某一部分写入

参数说明
str字符串
off开始偏移量。(从字符串的何处开始取)
lenoff开始向后取len个字符。(写入流)
String out = "E:\\\\out.txt";
try (FileWriter fileWriter = new FileWriter(out)) 
    char[] c = "天使只是别处的凡人,神仙不过他山的妖怪。".toCharArray();
    fileWriter.write(c, 10, 1);
    fileWriter.write(c, 11, 1);
    fileWriter.write(63);
    fileWriter.write(c, 17, 2);
    fileWriter.write(63);
    fileWriter.write("谢谢", 0, 2);
    fileWriter.write(46);
 catch (IOException e) 
    e.printStackTrace();

E:\\temp\\test\\out\\out.txt 结果:

神仙?妖怪?谢谢.

写字符(追加)

Files 版

try 
    final Path path2 = Paths.get("文件完整路径");
    byte[] buf = "\\n那唐僧内眼凡胎不识妖怪,反护着它……".getBytes();
    Files.write(path, buf, StandardOpenOption.APPEND);
 catch (IOException e) 
    e.printStackTrace();

利用完灭口

path.toFile().deleteOnExit(); 

BufferedWriter 版

try(BufferedWriter writer = new BufferedWriter(new FileWriter("E:\\\\out.txt", true)))

    writer.write("\\n天使只是别处的凡人,神仙不过他山的妖怪。笑虾如是说。");

PrintWriter 版

try(PrintWriter printWriter = new PrintWriter(new FileWriter("E:\\\\out.txt", true))) 

    printWriter.println("\\n天使只是别处的凡人,神仙不过他山的妖怪。笑虾如是说。");

FileOutputStream 版

try(FileOutputStream outputStream = new FileOutputStream("E:\\\\out.txt", true)) 
    outputStream.write("\\n天使只是别处的凡人,神仙不过他山的妖怪。笑虾如是说。".getBytes());

工具类

Apache Commons IO - FileUtils

读取整个文件到 String

File file = new File("E:\\\\int.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
System.out.println(content);

读取整个文件到 List<String>

List<String> lines = FileUtils.readLines(new File(in), Charset.defaultCharset());
lines.forEach(System.out::println);

逐行迭代

try(LineIterator it = FileUtils.lineIterator(new File("E:\\\\int.txt"), "UTF-8")) 
    while (it.hasNext()) 
        String line = it.nextLine();
        System.out.println(line);
    
 catch (IOException e) 
    e.printStackTrace();

读大文件推荐方案

  1. java.nio.file.Files.lines()
  2. Apache Common IO:FileUtils.lineIterator()

参考资料

java.nio.file.Files

以上是关于Java 学习笔记 - 读写字符文件的主要内容,如果未能解决你的问题,请参考以下文章

java IO 学习笔记

Java 学习笔记 - 按 Java 类型,读写字节文件

Java 学习笔记 - 按 Java 类型,读写字节文件

Java 学习笔记 - 按 Java 类型,读写字节文件

第一章 初到贵地 Win32异界类型

JAVA学习笔记 -- 读写XML