英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论