I am trying to design a file reader with some sort of GUI so I decided to use JOptionPane. I am a complete noob trying to learn java.
So far, I have managed to make my program produce a pop up for the file location, and also an error message if the program can't locate the file.
However, I cant get the results to display in one single box, it displays one for each line as I could only get it to work in the loop which would obviously do that. How do I go about displaying all the lines from the file in one output box?
package readtextfile;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Main
{
public static void main(String[] args) throws IOException
{
String file_name = JOptionPane.showInputDialog(null, "What's the File Location?");
//"C:/Users/MyBook/Documents/TestProgram/testdocument.txt"
try
{
ReadFile file = new ReadFile(file_name);
String[] arrayLines = file.OpenContents();
int i;
for (i=0; i<arrayLines.length; i++)
{
JOptionPane.showMessageDialog(null, arrayLines[i]);
}
}
//if there is an error, catch will produce error message
catch (IOException errorMessage) //errorMessage is a variable, IOException type
{
JOptionPane.showMessageDialog(null, "File Not Found!");
System.out.println(errorMessage.getMessage());
System.out.printf("File %s can not be found.\n\n", file_name ); //getMessage is a method of IOException
}
}
}
package readtextfile;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile
{
private String path;
public ReadFile(String file_path)
{
path = file_path;
}
int readLines() throws IOException
{
FileReader file = new FileReader(path);
BufferedReader buffer = new BufferedReader(file);
String aLine;
int numberOfLines = 0;
while ((aLine = buffer.readLine() ) !=null) //read each line until null value reached
{
numberOfLines++;
}
buffer.close();
return numberOfLines;
}
public String[] OpenContents() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader buffer = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i<numberOfLines; i++)
{
textData[i] = buffer.readLine();
}
buffer.close();
return textData;
}
}