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);
}
}
Related
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.
I have looked at this question Here and followed the answers. Yet the compiler is still complaining about a Null Pointer Exception. Here is my code blocks as to where the compiler is complaining:
public class readLogger {
DLQPush dlqPush = new DLQPush();
public String values[];
int condition = 2;
public BufferedReader reader = null;
public void readFile() {
try {
reader = new BufferedReader(new FileReader(
"/var/tmp/checkresults.log"));
} catch (FileNotFoundException e) {
System.err.println("ERROR: FILE NOT FOUND!\n");
}
String str = null;
try {
while ((str = reader.readLine()) != null) {
if (str.trim().length() == 0) {
continue;
}
values = str.split("\t");
System.out.println(values[1] + values[2]);
classifyStatus();
}
} catch (IOException e) {
e.printStackTrace();
}
}
The compiler is specifically complaining about this line:
while ((str = reader.readLine()) != null) {
And here is my Main class:
import java.io.IOException;
//import org.dcm4che3.tool.storescu.*;
public class Main {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) {
readLogger rLog = new readLogger();
rLog.readFile();
}
}
I have made the necessary fixes described in the link to the previous questions, yet my compiler is still complaining about it:
ERROR: FILE NOT FOUND!
Exception in thread "main" java.lang.NullPointerException
at readLogger.readFile(readLogger.java:25)
at Main.main(Main.java:13)
Nevermind the ERROR as I have exported this to a JAR file and put it in Linux and yet it still throws a NullPointer in Linux. Does anyone have any ideas as to how to fix the NullPointer exception?
Your reader variable is null by the time you invoke readLine in statement: while ((str = reader.readLine()) != null) {, since the file is not found (see your own print statement).
Hence you throw a NullPointerException by invoking readLine on a null BufferedReader reference.
The best practice here would be to stop the execution of your readFile method if the file is not found.
As an alternative you might want to at least check for null before invoking instance methods on your reader variable.
I've not been able to resolve the following exception in the code below. What is the problem with the way I use BufferedReader? I'm using BufferedReader inside the main method
OUTPUT :-
ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
// ParseFileName is used to get the file name from a file path
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"
import java.util.regex.Pattern;
import java.io.*;
public class ParseFileName {
//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = " + parts.length);
//Return the last element in the array of strings
return parts[parts.length -1];
}
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
}
UPDATE :
The following works:
public static void main(String[] args) throws FileNotFoundException, IOException {
However try.. catch still has some nagging issues for me:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex2) {
ex2.printStackTrace();
}
buffread dosent seem to get the file name. I get this error:
javac ParseFileName.java ParseFileName.java:67: cannot resolve symbol
symbol : variable buffread
location: class ParseFileName
while ((line = buffread.readLine())!= null) {
Add throws FileNotFoundException, IOException in the header of your method. It looks like just throwing the IOException will solve your problem, but incorporating both will allow you to tell if there was a problem with the file's existence or if something else went wrong (see catch statements below).
i.e.
public static void main(String[] args) throws FileNotFoundException, IOException {
Alternately, if you'd like to catch a specific exception and do something with it:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
// Do something with 'ex'
} catch (IOException ex2) {
// Do something with 'ex2'
}
Update to resolve the updated issue: This is just a simple scope problem which can be solved by declaring the BufferedReader outside of the try statement.
BufferedReader buffread = null;
try {
buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
...
You have to add throws statement into the signature of method main or wrap code in
try {
...
} catch (FileNotFoundException e) {
...
}
Your code can throw FileNotFoundException or IOException which is Checked Exception. You need to surround your code in a try-catch block or add a throws declaration in your main function.
The BufferReader can throw an exception if the file cannot be found or opened correctly.
This error message is telling you that you need to handle this exception. You can wrap the line where you create the BufferReader in a try/catch block. This will handle the case an IOException is thrown and print out the stack trace.
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread;
try
{
buffread= new BufferedReader (new FileReader("file.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
Another option is to add "throws IOException" to your method header.
public static void main(String[] args) throws IOException {
//...
}
This tells the compiler and callers of your method that you are choosing to not handle this exception and there is a chance it will be thrown.
What kind of problem may occur for this code?
I think even exception occurs, this code can throw the exception to its caller.
So it does NOT generate any trouble.
How can I improve it?
public static void cat(File named) {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(named, “r”);
while ((line = input.readLine()) != null {
System.out.println(line);
}
return;
} finally {
if (input != null) {
input.close();
}
}
}
The code has to throw the IOException - try editing your code with eclipse and you would also get a suggestion to throw the Exception.
Also Java 1.7 has the new concept of "try-with-resources" - see the try statement below.
The resource used in try (...) is closed automatically.
public static void cat(File named) throws IOException
{
try (RandomAccessFile input = new RandomAccessFile(named, "r"))
{
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
}
What kind of problem may occur for this code?
public RandomAccessFile throws FileNotFoundException.
public final String readLine() throws IOException.
public void close() throws IOException.
Since public class FileNotFoundException
extends IOException
You can change your method to:
public static void cat(File named) throws IOException
And now you don't need a try-catch blocks.
And the caller should catch the exception thrown by the method.
But why don't you want to catch the exceptions?
add the throws declaration in your method , and then caller of this method should have try catch block for this exception .
public static void cat(File named) throws IOException {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(named, "r");
while ((line = input.readLine()) != null ){
System.out.println(line);
}
return;
} finally {
if (input != null) {
input.close();
}
}
}
//caller
try{
Class.cat(new File("abc.txt"));
}catch(IOException e)
{
//
}
This program is compiling though not working. It just handling the opening file exception. Please help me.Thanks for your time.
import java.io.*;
import java.util.Scanner;
public class ReadingFile {
/**
* #param args
*/
public static void main(String[] args) {
ReadingFile rf = new ReadingFile();
rf.printOnScr();
}
private BufferedReader openFile(String meString){
Scanner sc = new Scanner(System.in);
BufferedReader bf = null;
while (bf == null) {
try {
System.out.println("Enter a file name");
String fileName = sc.nextLine();
FileReader b = new FileReader(fileName);
bf = new BufferedReader(b);
} catch (IOException e) {
System.out.println("The file you are trying to open dose not exist.");
}
}
return bf;
}
private void printOnScr() {
BufferedReader br = openFile("Please enter a file");
try {
while(true){
String line = br.readLine();
if(line == null) break;
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("The line you are trying to access have problem/s");
}
}
}
Very probably you're not specifying the correct path to the file when you type it. It should either be an absolute path or a relative path based at your current working directory. To see exactly what's happening, though, you'll need to look at the exception that's thrown. Either print it out with
e.printStackTrace()
or wrap it in an unchecked exception:
throw new IllegalStateException(e);
or let IOException be thrown from openFile(), through printOnScr(), and out of main()