Reading a txt file in a Java GUI - java

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?

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));
}
});
}
});

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

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 the JLabel'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;

Use java.io to open a file stream.
Read content from file by lines or bytes.
Append content to StringBuilder or StringBuffer
Set StringBuilder or StringBuffer to JLable.text.
But I recommend using JTextArea..
You don't need to put this file in src folder.

Related

How to read multiple files one by one and display in the same text area in java swing?

I'm doing some coding for an assignment. I'm using java swing to do it. I need to know that how should change my code to display multiple files content in a text area.
I've tried some codes. I added one jButton and one jTextArea to read multiple files. I already know something about setMultiSelectionEnabled(true) and getSelectedFiles().
//This is my code inside the jButton
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(null);
File files = chooser.getSelectedFiles();
String filename = files.getAbsolutePath();
try{
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
jTextArea1.read(br, null);
br.close();
jTextArea1.requestFocus();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
I can only get one file content into my text area yet. Please help me to develop this. Thank you!
If you want multiple files in a single text area, then you can't use the read(...) method.
Instead you will need to read each file line by line and the add the text to the text area using the append(...) method.
try this code:
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(null);
File[] files = chooser.getSelectedFiles();
// String filename = files.getAbsolutePath();
for(File f:files){
FileReader reader = new FileReader(f);
BufferedReader br = new BufferedReader(reader);
while( (line = br.readLine()) != null ) {
jTextArea1.append(line);
}
br.close();
//jTextArea1.requestFocus();
}

Read text file from resource folder and populate jTextArea (NetBeans Java)

StringBuilder result = new StringBuilder("");
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("DBase.dat").getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
jTextArea1.setText(result.toString());
scanner.close();
} catch (FileNotFoundException ex) {
}
I am new to JAVA and netBeans I am using this code to read a text file from resources folder and then populate jTextArea from that file. But I am getting Errors. I want to read textfile line by line not all the text at once...
Please Help me what should I do.
I am pasting a picture too...
Project Picture
try something like that:
File file = new File(classLoader.getResource("DBase.dat").getPath());

Displaying Data from Text File on a Graph

Reading a .txt file using a file chooser and bufferedreader, I now need to display the data on a line graph. So the title from the text file will be at the top, with the axis labelled using the names given in the text file and the numbers plotted to make up the line graph. No idea where to begin with this as a complete beginner.
Since you use local classes, you can capture the text variable (your JTextArea) and use it in the action listener code:
class openaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Open a Text File");
int result = chooser.showOpenDialog(null);
// ^^^ renamed this, so it doesn't hide 'text'
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
// Read in lines.
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
// Append each line, plus a newline, to the text area.
br.lines().forEach(line -> text.append(line + System.lineSeparator()));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

How to save the text file in a path given by JFileChooser?

I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.

How to read from a file not in Eclipse in Java

I have a file which is needed for running tests - this file needs to be personalized (name and password) by whomever is running the test. I do not want to store this file in Eclipse (since it would need to be changed by whomever runs the test; also it would be storing personal info in the repo), so I have it in my home folder (/home/conrad/ssl.properties). How can I point my program to this file?
I've tried:
InputStream sslConfigStream = MyClass.class
.getClassLoader()
.getResourceAsStream("/home/" + name + "/ssl.properties");
I've also tried:
MyClass.class.getClassLoader();
InputStream sslConfigStream = ClassLoader
.getSystemResourceAsStream("/home/" + name + "/ssl.properties");
Both of these give me a RuntimeException because the sslConfigStream is null. Any help is appreciated!
Use a FileInputStream to read data from a file. The constructor takes a string path (or a File object, which encapsulates string path).
Note 1: A "resource" is a file which is in the classpath (alongside your java/class files). Since you don't want to store your file as a resource because you don't want it in your repo, ClassLoader.getSystemResourceAsStream() is not what you want.
Note 2: You should use a cross-platform way of getting a file in a home directory, as follows:
File homeDir = new File(System.getProperty("user.home"));
File propertiesFile = new File(homeDir, "ssl.properties");
InputStream sslConfigStream = new FileInputStream("/home/" + name + "/ssl.properties")
You can simplify your work, using Java's 7 method:
public static void main(String[] args) {
String fileName = "/path/to/your/file/ssl.properties";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also improve your way of reading properties file, using Properties class and forget about reading and parsing your .properties file:
http://www.mkyong.com/java/java-properties-file-examples/
Is this a graphics program (ie. using the Swing library)? If so it is a pretty simple task of using a JFileChooser.
http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html
JFileChooser f = new JFileChooser();
int rval = f.showOpenDialog(this);
if (rval == JFileChooser.APPROVE_OPTION) {
// Do something with file called f
}
You can also use Scanner to read the file.
String fileContent = "";
try {
Scanner scan = new Scanner(
new File( System.getProperty("user.home")+"/ssl.properties" ));
while(scan.hasNextLine()) {
fileContent += scan.nextLine();
}
scan.close();
} catch(FileNotFoundException e) {
}

Categories