代码之家  ›  专栏  ›  技术社区  ›  user8678484

使用Java将文本从一个文件反转和存储到另一个文件时,大小会减小

  •  1
  • user8678484  · 技术社区  · 8 年前

    我做了这个家庭作业练习,从一个文本文件中读取文本,并将其反向存储到另一个新文件中。这是代码:

    import java.util.*;
    import java.io.*;
    
      public class FileEcho {
    
    File file;
    Scanner scanner;
    String filename = "words.txt";
    File file1 ;
                PrintWriter pw ;
    void echo() {
        try {
            String line;
    
            file = new File( filename);
            scanner = new Scanner( file );
            file1 = new File("brabuhr.txt");
            pw = new PrintWriter(file1);
    
    
            while (scanner.hasNextLine()) {
                line = scanner.nextLine();
                String s = new StringBuilder(line).reverse().toString();
    
                pw.println(s);
            }
            scanner.close();
        } catch(FileNotFoundException e) {
            System.out.println( "Could not find or open file <"+filename+">\n"+e 
     );
        } 
    }
    
    public static void main(String[] args) {
        new FileEcho().echo();
    }
     }
    

    这是一张照片 Picture here

    问题是:为什么新生成的文件虽然具有相同的字符,但大小有所减小?

    如果有人能解释一下就好了,因为即使是我的教授也不知道为什么会这样。

    附笔;文件的上下文只是字典中的一些单词。 还有其他学生的电脑,所以问题不是来自我的电脑

    1 回复  |  直到 8 年前
        1
  •  0
  •   M. le Rutte    8 年前

    问题是您从未关闭输出流 pw ,因此任何挂起的输出都不会写入基础文件。这可能会导致文件被截断。

    您应该用 pw.close() 在一个 finally ,或尝试使用资源。

    try (pw = new PrintWriter(file1)) {
       while (scanner.hasNextLine()) {
          line = scanner.nextLine();
          String s = new StringBuilder(line).reverse().toString();
          pw.println(s);
      }
    }
    

    您的实现可以简化为以下内容:

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class FileEcho {
        void echo() throws IOException {
            try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
                Files.lines(Paths.get("words.txt"))
                    .map(s -> new StringBuilder(s).reverse().toString())
                    .forEach(pw::println);
            }
        }
    
        public static void main(String[] args) throws IOException {
            new FileEcho().echo();
        }
    }
    

    PrintWriter pw 自动关闭。