I'm trying to load data from a text file into a JList using WindowBuilder with the click of a button. As you can see from the code below I'm getting few exceptions that I can't seem to fix. Importing java.io.FileReader does not help.
I have a separate class file with the code for my Score vector.
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sLine;
Vector<Score> scoreVec = new Vector<Score>();
//Here I am getting a FileNotFoundException for (new FileReader("scores.txt")
BufferedReader in = new BufferedReader(new FileReader("scores.txt"));
//Here I am getting an IOException for in.readLine()
while ((sLine = in.readLine()) != null)
{
scoreVec.addElement(new Score(sLine));
}
//this is also throwing an IOException
in.close();
//Placeholders until I get the rest of the program working
System.out.println(scoreVec.get(1).name);
System.out.println(scoreVec.get(1).country);
}
});
btnLoadData.setBounds(10, 227, 89, 23);
frame.getContentPane().add(btnLoadData);
You need to catch and handle the raised exceptions, for example...
public void actionPerformed(ActionEvent arg0) {
String sLine;
Vector<Score> scoreVec = new Vector<Score>();
//Here I am getting a FileNotFoundException for (new FileReader("scores.txt")
try (BufferedReader in = new BufferedReader(new FileReader("scores.txt"))) {
//Here I am getting an IOException for in.readLine()
while ((sLine = in.readLine()) != null) {
scoreVec.addElement(new Score(sLine));
}
} catch (IOException exp) {
exp.printStackTrace();
}
//Placeholders until I get the rest of the program working
System.out.println(scoreVec.get(1).name);
System.out.println(scoreVec.get(1).country);
}
See the Exceptions trail and The try-with-resources Statement for more details
What is the real path of relevant class and scores.txt
I not recomment but only one you can use full path of scores.txt file.
Related
`public void actionPerformed(ActionEvent e) {
if(e.getSource()==EnterLogin) {
CorrectLogin();
}
}
private void CorrectLogin() throws IOException {
String filename = ("accounts.txt");
FileReader fr1= new FileReader (filename);
BufferedReader br1 = new BufferedReader(fr1);
String accounts[][] = new String[10][2];
for(int k=0 ; k<10; k++ ){ `
reading in from an external txt file
`String line = br1.readLine();
String split [] = line.split(",");
accounts [k][0] = split [0];
accounts [k][1] = split [1];
System.out.println(accounts[1][1]);
}
}`
You didn’t actually ask a question. I assume you want to know what to do about the error message in your title.
You can answer that question yourself by deciding what should happen if CorrectLogin cannot read accounts.txt for any reason (such as the file not existing).
I assume your application needs the user to log in before it can provide any more functionality, so you probably should show the user an error dialog, then refuse to proceed any further.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == EnterLogin) {
try {
CorrectLogin();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
EnterLogin.getTopLevelAncestor(),
"Cannot log in.\n\n" + e,
"Login Failure",
JOptionPane.ERROR_MESSAGE);
// Application can't work without a login, so do not keep going.
return;
}
}
}
I am developing a simple GUI Calculator with the Java Swing library and bumped into the problem which I couldn't find a solution. I am just studying Java, so do not judge me strictly if the problem is simple.
The main idea of my problem is that I am trying to use Java.io "File handling" to save the number into the file and get that number when you re-open the calculator into the text field.
Here is the code:
public void actionPerformed (ActionEvent e)
{
//---------------------------------------------------------------
if (e.getSource() == button_save) {
save = mytext.getText();
writeF(save); // problem is here "Unhandled exception type IOException"
}
else if (e.getSource() == button_recall) {
recall = readF(); // also here
mytext.setText(recall);
}
User-defined method
public static void writeF(String memory)throws IOException{
FileWriter writehandle = new FileWriter("C:\\Users\\Public\\Documents\\memory.txt");
BufferedWriter bw = new BufferedWriter(writehandle);
bw.write(memory);
bw.close();
writehandle.close();
}
public static String readF()throws IOException{
FileReader readhandle = new FileReader("C:\\Users\\Public\\Documents\\memory.txt");
BufferedReader br = new BufferedReader(readhandle);
String num = br.readLine();
br.close();
readhandle.close();
return num;
}
The full code you can find here
Solution:
else if (e.getSource() == button_save) {
save = mytext.getText();
try
{
writeF(save);
}
catch (IOException e1)
{
e1.printStackTrace();
} // problem is here "Unhandled exception type IOException"
}
else if (e.getSource() == button_recall) {
try
{
recall = readF();
}
catch (IOException e1)
{
e1.printStackTrace();
} // also here
mytext.setText(recall);
}
I need to read a txt file and store my data to a treeSet.
public class UrbanPopulationStatistics {
private Set<UrbanPopulation> popSet;
private File file;
private BufferedReader br;
public UrbanPopulationStatistics(String fileName) throws IOException {
this.popSet = new TreeSet<>();
readFile("population.txt");
}
private void readFile(String fileName) throws IOException {
try {
br = new BufferedReader(new FileReader(fileName));
String line;
while ((line=br.readLine()) != null) {
String[] array = line.split("/");
popSet.add(new UrbanPopulation(array[0], Integer.parseInt(array[1]), Integer.parseInt(array[4])));
}
} catch (IOException e) {
e.printStackTrace();
}
br.close();
}
#Override
public String toString() {
String s = popSet.toString().replaceAll(", ", "");
return "UrbanPopulationStatistics:\n" + s.substring(1, s.length() - 1) + "\n";
}
public static void main(String[] args) throws IOException {
UrbanPopulationStatistics stats = new UrbanPopulationStatistics("population.txt");
System.out.println(stats);
}
}
I have tried to turn what the buffered reader reads into an array and then add it into my treeSet, but I get the error: Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
You have an extra period after parseInt at Integer.parseInt.(array[4])));.
Be careful when writing code. Syntax errors don't show up "nicely", i.e. the error message is not very helpful in most cases. It does show you the approximate location of the error though.
The problem with your code is you are not storing what you read from the buffer (and hence reading twice from the buffer). You need to assign what you read in a variable to check for null as below:
private void readFile(String fileName) throws IOException {
try {
br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
String[] array = line.split("/");
popSet.add(new UrbanPopulation(array[0], Integer.parseInt(array[1]), Integer.parseInt(array[4])));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
}
Also I would close the BufferedReader in the finally block to avoid resource leaks.
I tried to reproduce the error using your code, but it doesn't happened. Your code is ok.
UnsupportedOperationException are exceptions that can happen when you try to add an element in a collection.
But TreeSet implements the add method.
I am trying to write a program which takes a java file as input (which is specified in the program) and reads through it line by line. If a line is longer than 80 characters it throws an exception, if the exception is thrown the program prints the line that is too long and continues the process with the rest of the program.
import java.io.*;
import java.util.*;
public class LinePolice
{
public static void main(String[] args) throws LinePoliceTooLongException
{
try
{
File file = new File("NameOrientation.java");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
LinePoliceTooLongException x = new LinePoliceTooLongException(line);
if (line.length() > 80)
throw x;
}
fileReader.close();
}
catch (IOException e)
{
}
}
}
public class LinePoliceTooLongException extends Exception
{
LinePoliceTooLongException(String message)
{
super(message);
}
}
When I run it with the following file it picks up the first line longer than 80 but does not continue through the file.
import java.awt.*;
import javax.swing.*;
public class NameOrientation
{
public static void main(String[] args)
{
JFrame frame = new JFrame("NameOrientation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel primary = new JPanel();
primary.setBackground(Color.green);
primary.setPreferredSize(new Dimension(250, 250));
JLabel label1 = new JLabel("********************************************************");
JLabel label2 = new JLabel("**************************************************************");
primary.add(label1);
primary.add(label2);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
If possible can someone tell me where I am going wrong and what I can do to try and get this to work. Thanks for any and all help
while ((line = bufferedReader.readLine()) != null)
{
LinePoliceTooLongException x = new LinePoliceTooLongException(line);
try{
if (line.length() > 80)
throw x;
}catch(LinePoliceTooLongException le){
System.out.println("Line:"+line);
}
}
Since you are throwing LinePoliceTooLongException from while loop and not catching it, you are unable to continue for rest of the lines. You have to catch the exception in while loop itself.
In your code you are creating the exception
LinePoliceTooLongException x = new LinePoliceTooLongException(line);
throwing it and you are not catching it. Thats is why your program is not completing properly. I think that you would have understood that by now.
To solve this, you can add catch block to catch the exception that you have just thrown. If you do this, that will be really a horrible, there is no meaning in throwing an exception and catching it right after it's thrown. Whatever you want to do in catch block do it inside your if and don't throw any exception.
while ((line = bufferedReader.readLine()) != null)
{
if (line.length() > 80){
System.out.println("Line is more than 80 characters and can not be processed: " + line);
}
}
public void tokenize(){
// attempt creating a reader for the input
reader = this.newReader();
while((line = reader.readLine())!=null){
tokenizer = new StringTokenizer(line);
while(tokenizer.hasMoreTokens()){
toke = (tokenizer.nextToken().trim());
this.tokenType(toke);
//System.out.println(this.tokenType(toke));
}
}
}
private BufferedReader newReader(){
try {//attempt to read the file
reader = new BufferedReader(new FileReader("Input.txt"));
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
catch(IOException e){
System.out.println("I/O Exception");
}
return reader;
}
I thought I had handled it within newReader() but it appears to be unreachable. Eclipse recommends a throws but I don't understand what that's doing, or if it's even solving the problem?
Appreciate the help!
If you don't know how to handle an IOException in this method, then it means that it's not the responsibility of the method to handle it, and it should thus be thrown by the method.
The reader should be closed in this method, though, since this method opens it:
public void tokenize() throws IOException {
BufferedReader reader = null;
try {
// attempt creating a reader for the input
reader = this.newReader();
...
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
// nothing to do anymore: ignoring
}
}
}
}
Also, note that unless your class is itself a kind of Reader wrapping another reader, and thus has a close method, the reader shouldn't be an instance field. It should be a local variable as shown in my example.