java - 如何提取 .txt 文件的内容

标签 java jframe

我正在用 java 浏览一个 .txt 文件...如何提取该文本文件中的内容?

我浏览.txt文件的源代码是:

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));

chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
  public boolean accept(File f) {
    return f.getName().toLowerCase().endsWith(".txt")
        || f.isDirectory();
  }

  public String getDescription() {
    return ".txt Files";
  }
});

int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
  String name = chooser.getSelectedFile().getName();
  jTextField3.setText(name);
}
else
{
    JOptionPane.showMessageDialog(null,
                    "You must select one Audieo File to be the reference.", "Aborting...",
                    JOptionPane.WARNING_MESSAGE);
}

最佳答案

如果你想读取文本文件的内容,你需要使用BufferedReader。然后使用readLine()方法读取内容。文件结尾由 null 指示。

SSCCE:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}  

取自 Mykong

关于java - 如何提取 .txt 文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278687/

相关文章:

java - ExecutorService 与异步注解

java - 将 ExceptionDescribe 转换为字符串

java - JFrame 和 JOptionPane

java - JFrame 表单创建(多行、多列和输入)

Java swing JLabel 未显示

java - 如何使 JTable 适合 JFrame 的大小?

java - Spring AOP : Trying to use for logging but getting IllegalArgumentException

java - 我在遍历文本文件时创建目录时遇到问题

java - 枚举 JFrame 上的所有控件

java - 使用 HttpClient 4.1.1 避免循环重定向