Access variable in try block - java

I want to remove the throws FileNotFoundException from the method head and put it into it.
public static String[] read(String file) throws FileNotFoundException {
But then I can't access in (the scanner) anymore! How to handle that?
public static String[] read(String file) {
try {
Scanner in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
// ...
in.close();
// ...
}

Just use try-with-resources so you dont have to worry about closing the scanner object.
try (Scanner in = new Scanner(new FileReader(file))) {
//Your code
}
catch (Exception e) {
}

you can use try with ressource, that permit to close automaticaly your in.
like that
Scanner in ;
try ( in = new Scanner(new FileReader(file))) {
}
catch (Exception e) {
}

The variable in is out of scope outside the try block. You can either do this:
public static String[] read(String file) {
Scanner in = null;
try {
in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
finally() {
in.close();
}
// ...
}
Or better yet, try with resources
public static String[] read(String file) {
try (Scanner in = new Scanner(new FileReader(file))){
String line = in.nextLine();
// whatever comes next
}
catch (Exception e) {
}
// right here, the scanner object will be already closed
return ...;
}

The in variable is locally scoped to the try block. You can either declared the variable before the try block, or close in within the try block. There's not much use in closing it if it never successfully opened.

Related

Running multiple try statements within each other?

Would this be problematic and run into issues?
Example:
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
try {
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (FileNotFoundException ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
}
If it is problematic, what other approach should I look to?
Too many try-catch would complicate code and reduce the code readability which will lead to swallowing an exception and its much more worse than performance issues as it can crash your system unexpectedly.
Here is an example of swallowing an exception and its side effects (multiple point of failures like NPE etc.).
public static void main(String[] args) {
String dataFromFile = null, dataFromDataBase = null;
try {
try {
dataFromFile = readFile();
} catch (IOException e) {
// ignore exception
// String dataFromFile will be set to null
// as there was an exception
}
// imagine many lines of code here
dataFromDataBase = readDatabase(dataFromFile.getKey());
} catch (IOException e) {
// ignore exception
}
// imagine many lines of code here
System.out.println(dataFromFile.replace(" ", ""));
//imagine many lines of code here
System.out.println(dataFromDataBase.getKey());
}
private static String readFile() throws IOException {
// throws ioexception
}
private static String readDatabase(String key) throws IOException {
// throws ioexception
}
If you are expecting multiple points in a single method that can throw exceptions then club them into one try-catch and handle them appropriately. Again there can be exception to this specific question but you should always try to reduce multiple try-catch in single method.
Unless you are doing something specific with an exception, use single Exception clause to handle all exception and log details or throw it to the caller to handle it in its own specific ways.
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (Exception ex) {
// Display Exception stuff details
}
}
In this example I see no reason to start a new try statement. why not do this?
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
But no, there would be no problem. it just looks bad. but sometimes needed I guess.

BufferedWriter writing to console instead of text file

These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}

Resolving IOException, FileNotFoundException when using FileReader

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.

How to read line from txt?

How can I read line from text? Look at my code:
public static String getTemplateFromFile() {
String name = null;
try {
BufferedReader reader = new BufferedReader(new
FileReader(
"http://localhost:8080/blog/resources/cache/templateName.txt"));
name = reader.readLine();
//name="TEST";
//NULL anyway
reader.close();
}
catch (Exception e) {
}
return name;
}
Also I have got secnod version, but my server freeze.
public static String getTemplateFromFile() {
String name = null;
/*
try {
URL url = new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
Scanner s = new Scanner(url.openStream());
name=s.nextLine();
s.close();
}
catch(IOException ex) {
ex.printStackTrace();
}*/
return name;
}
I think it can't close connection or something.
It returns me NULL even I say name="TEST"; in try construction.
FileReader is exactly that – a class that reads from files, not HTTP requests.
You're getting an invalid file path exception, which you're then ignoring in your evil empty catch block.
Instead, you should use URLConnection.
Try this
try{
URL reader=new URL("http://localhost:8080/blog/resources/cache/templateName.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(reader.openStream()));
name = br.readLine();
//name="TEST";
br.close();
}catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
AFAIK, URL#openStream() internally calls URL#openConnection() which creates an instance of URLConnection and calls URLConnection#getInputStream() on it.

How to correctly handle this IOException?

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.

Categories