0

I am browsing a .txt file in java... How to extract the contents in that text file ?

My source code for browsing .txt file is:

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);
}
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
user3397667
  • 11
  • 1
  • 1
  • 2

1 Answers1

1

If you want to read the contents of the text file, you need to use a BufferedReader. Then use the readLine() method to read the contents. End of file is indicated by a 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();
        } 

    }
}  

Taken from Mykong

An SO User
  • 24,612
  • 35
  • 133
  • 221
  • I am using this code but show "change type of br to bufferreader" this error... What can i do? Please help me.. – user3397667 Mar 09 '14 at 13:05