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

24

如何读取并展示 .txt 文件中的数据?


1
在编程方面,一些更多的问题信息可能有助于您获得更好的答案。关于您已知的内容、您认为自己所知道的内容等等的信息可以帮助确定是否有任何具体的问题需要解答。 - Ryan Guill
9个回答

48
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));

接下来,你可以使用in.readLine();逐行读取。如果要一直读到末尾,则可以编写以下while循环:

String line;
while((line = in.readLine()) != null)
{
    System.out.println(line);
}
in.close();

1
如何检查文件的长度? - It's Willem

24

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

您可以通过以下方式从文件创建一个Scanner

Scanner fileIn = new Scanner(new File(thePathToYourFile));

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

fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file

同时,您可以使用以下代码检查是否还有更多文本:

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

当你读取了文本并将其保存在String中后,你可以使用以下方式将这个字符串打印到命令行中:

System.out.print(aString);
System.out.println(aString);

发布的链接包含Scanner类的完整规范。 它将有助于您处理其他任何想要进行的操作。


我总是忘记Scanner,从未真正使用过它...可惜它需要一个字符集名称 :( (我建议始终明确指定字符集) - Jon Skeet
好的,我假设场景尽可能简单。添加字符集可能会令人困惑。通常情况下,您不需要担心它。 - jjnguy
但是,扫描仪非常适合快速读取文本文件。 - jjnguy
我很少想让我的代码依赖于系统,如果省略字符集,这就是发生的情况。如果我确实想使用默认字符集,我会明确地这样做(Charset.defaultCharset().name())。字符编码很麻烦,但是在我看来,越早理解它们就越好。 - Jon Skeet
我猜我宁愿迎合提问者的期望。他/她可能希望使他们的代码具有系统无关性。 - jjnguy

11

通常情况下:

  • 为文件创建一个FileInputStream
  • 创建一个InputStreamReader,将输入流包装起来,并指定正确的编码方式
  • 可选地,可以在InputStreamReader周围创建一个BufferedReader,这样更容易一次读取一行。
  • 读取数据直到没有更多数据(例如,readLine返回null)。
  • 在进行操作时显示数据或将其缓存以供稍后使用。

如果您需要比这更详细的帮助,请在问题中更具体说明。


7

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

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();

1
以下是代码,您可以尝试使用scanner类读取文件并在Java中显示。代码将从用户那里读取文件名并打印数据(记事本VIM文件)。
import java.io.*;
import java.util.Scanner;
import java.io.*;

public class TestRead
{
public static void main(String[] input)
{
    String fname;
    Scanner scan = new Scanner(System.in);

    /* enter filename with extension to open and read its content */

    System.out.print("Enter File Name to Open (with extension like file.txt) : ");
    fname = scan.nextLine();

    /* this will reference only one line at a time */

    String line = null;
    try
    {
        /* FileReader reads text files in the default encoding */
        FileReader fileReader = new FileReader(fname);

        /* always wrap the FileReader in BufferedReader */
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null)
        {
            System.out.println(line);
        }

        /* always close the file after use */
        bufferedReader.close();
    }
    catch(IOException ex)
    {
        System.out.println("Error reading file named '" + fname + "'");
    }
}

}


0
在Java 8中,你可以使用以下代码轻松读取整个文件:
public String read(String file) throws IOException {
  return new String(Files.readAllBytes(Paths.get(file)));
}

或者如果它是一个资源:

public String read(String file) throws IOException {
  URL url = Resources.getResource(file);
  return Resources.toString(url, Charsets.UTF_8);
}

0
如果你想要使用一些捷径,你可以使用Apache Commons IO
import org.apache.commons.io.FileUtils;

String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);

:-)


0
public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

1
你好,欢迎来到StackOverflow。请花些时间阅读帮助页面,特别是名为“我可以在这里问什么话题?”和“我应该避免提出哪些类型的问题?”的部分。更重要的是,请阅读Stack Overflow问题清单。你可能还想了解最小化、完整化和可验证示例 - Ataur Rahman Munna

-2

你很可能想要使用FileInputStream类:

int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));

while( (character = inputStream.read()) != -1)
        buffer.append((char) character);

inputStream.close();
System.out.println(buffer);

你也需要捕获一些由read()方法和FileInputStream构造函数抛出的异常,但这些是针对你的项目特定的实现细节。

2
inputStream.read() 不会返回一个 字符 - 它返回一个 字节(作为 int,尽管它们非常不同)。要读取文本,您应该使用 Reader。 - Jon Skeet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接