从文件中读取数据并以字符串形式返回相同的数据。

huangapple go评论63阅读模式
英文:

Read data from file and return the same data in a string

问题

从文件中读取数据并将相同的数据作为字符串返回
它只返回最后一行,我如何返回文件中的相同数据?

文件


    这是测试文件。
    这是测试文件!
    测试
    测试文件
    
    
    
    
    xxas   测试
    
    文件
    
    !  测试
    
    测试

   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);
    
    }
    }
英文:

Read data from the file and return the same data in a string
It only returns the last line, how can I return the same data in the file?

File


    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);
    
    }
    }

答案1

得分: 1

输入变量应该是一个StringBuilder,并使用append方法:

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

input variable should be a StringBuilder and use append:

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

答案2

得分: 0

你可以简单地将每一行追加到 'input' 变量中:

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

从性能角度考虑,将 'input' 声明为 StringBuilder 可能更好。

另一种选项是将 System.out.println(input); 插入到 while 循环中。

英文:

You can simply append each line to 'input':

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

And performance wise it might be better to declare 'input' as a StringBuilder

Another option is to insert System.out.println(input); into the while loop

huangapple
  • 本文由 发表于 2020年7月29日 17:23:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63150431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定