【问题标题】:Read data from file and return the same data in a string从文件中读取数据并以字符串形式返回相同的数据
【发布时间】:2020-11-18 20:33:26
【问题描述】:

从文件中读取数据并以字符串形式返回相同的数据 它只返回最后一行,如何在文件中返回相同的数据?

文件


    This is test file.
    This is test file!
    Test
    test file
    
    
    
    
    xxas   test
    
    fil
    
    !  test
    
    te

   import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Read {
        static String input = "";
    public static void main (String [] args) throws FileNotFoundException {
            Scanner file = new Scanner(new File("Example.txt"));
            while(file.hasNextLine()){
                input = file.nextLine();
            }
            System.out.println(input);
    
    }
    }

【问题讨论】:

  • System.out.println(Files.readAllLines("Example.txt"));
  • 你应该在循环内部打印输入,而不是在它之后。

标签: java file java.util.scanner


【解决方案1】:

输入变量应该是 StringBuilder 并使用 append:

Scanner file = new Scanner(new File("Example.txt"));
            while(file.hasNextLine()){
                input.append(file.nextLine());
            }
            System.out.println(input.toString());

【讨论】:

  • 如果我想清除StringBuilder,我该怎么做?我试过 setLength(0) 但它不起作用。
  • 如果设置 setLenght(0) 不起作用,请尝试此线程中的第二个选项:stackoverflow.com/questions/5192512/…
【解决方案2】:

您可以简单地将每一行附加到“输入”:

input += file.nextLine() + "\n";

在性能方面,将“输入”声明为StringBuilder 可能会更好

另一个选项是插入 System.out.println(input);进入while循环

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多