问题
All I want to do is display the entire contents of a txt file. How would I go about doing this? I'm assuming that I will set the text of a JLabel to be a string that contains the entire file, but how do I get the entire file into a string? Also, does the txt file go in the src folder in Eclipse?
回答1:
This code to display the selected file contents in you Jtext area
static void readin(String fn, JTextComponent pane)
{
try
{
FileReader fr = new FileReader(fn);
pane.read(fr, null);
fr.close();
}
catch (IOException e)
{
System.err.println(e);
}
}
To choose the file
String cwd = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(cwd);
JButton filebutton = new JButton("Choose");
filebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (jfc.showOpenDialog(frame) !=JFileChooser.APPROVE_OPTION)
return;
File f = jfc.getSelectedFile();
readin(f.toString(), textpane);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setCursor(Cursor.
getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
});
}
});
回答2:
All I want to do is display the entire contents of a txt file. How would I go about doing this? I'm assuming that I will set the text of a JLabel to be a string that contains the entire file but how do I get the entire file into a string?
You would be better of using a JTextArea to do this. You can also look at the read() method.
does the txt file go in the src folder in Eclipse?
Nope. You can read files from any where. The tutorial on "Reading, Writing, and Creating Files" would be a good place to start
回答3:
- create text file in your project's working folder
- read your text file line by line
- store the line contents in
stringBuilder
variable - then append next line contents to
stringBuilder
variable - then assign the content of your
StringBuilder
variable to theJLabel
's text property
But it is not good idea to store whole file's data into JLabel
, use JTextArea
or any other text containers.
Read your file like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
now assign value of everything to JLabel
or JTextArea
JLabel1.text=everything;
回答4:
- Use
java.io
to open a file stream. - Read content from file by lines or bytes.
- Append content to
StringBuilder
orStringBuffer
- Set
StringBuilder
orStringBuffer
toJLable.text
.
But I recommend using JTextArea
..
You don't need to put this file in src folder.
来源:https://stackoverflow.com/questions/13667041/reading-a-txt-file-in-a-java-gui