Reputation:
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?
Upvotes: 0
Views: 30274
Reputation: 17655
stringBuilder
variablestringBuilder
variableStringBuilder
variable to the JLabel
's text propertyBut 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;
Upvotes: 2
Reputation: 772
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));
}
});
}
});
Upvotes: 4
Reputation: 6783
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
Upvotes: 3
Reputation: 3633
java.io
to open a file stream.StringBuilder
or StringBuffer
StringBuilder
or StringBuffer
to JLable.text
.But I recommend using JTextArea
..
You don't need to put this file in src folder.
Upvotes: 1