从.txt文件中读取和显示数据

Jes*_*ssy 22 java

如何从.txt文件中读取和显示数据?

kev*_*314 45

BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Run Code Online (Sandbox Code Playgroud)

然后,你可以使用in.readLine(); 一次读一行.要读到最后,请写一个while循环:

String line;
while((line = in.readLine()) != null)
{
    System.out.println(line);
}
in.close();
Run Code Online (Sandbox Code Playgroud)

  • 记得添加in.close(); 在代码的最后. (3认同)

jjn*_*guy 22

如果您的文件是严格的文本,我更喜欢使用java.util.Scanner该类.

您可以通过以下方式创建Scanner文件:

Scanner fileIn = new Scanner(new File(thePathToYourFile));
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下方法从文件中读取文本:

fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
Run Code Online (Sandbox Code Playgroud)

并且,您可以检查是否还有其他文字:

fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Run Code Online (Sandbox Code Playgroud)

一旦读完文本并将其保存到a中String,就可以将字符串打印到命令行:

System.out.print(aString);
System.out.println(aString);
Run Code Online (Sandbox Code Playgroud)

发布的链接包含Scanner类的完整规范.帮助您完成其他任何您可能想做的事情将会很有帮助.


Jon*_*eet 10

一般来说:

  • FileInputStream为文件创建一个.
  • 创建InputStreamReader包装输入流,指定正确的编码
  • 可选择创建一个BufferedReader周围InputStreamReader,这使得一次读取一行更简单.
  • 读取,直到没有更多数据(例如readLine返回null)
  • 随时显示数据或将其缓冲以供日后使用.

如果您需要更多帮助,请在您的问题中更具体.


Gre*_*Noe 7

我喜欢这段代码,用它来将文件加载到一个String中:

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Run Code Online (Sandbox Code Playgroud)