FileNotFoundException not caught by IOException - java

In my program I want to read a file and then analyze it. To do this I made this simple code :
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader("E:\\Users\\myFile.txt");
br = new BufferedReader(fr);
[...]
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Unfortunately when my file doesn't exist I have a java.io.FileNotFoundException exception that is thrown. But when I read the doc of java.io.FileNotFoundException I can see that java.io.IOExceptionis a superclass of java.io.FileNotFoundException.
So, why does java.io.FileNotFoundException is not caught by catch (IOException ex)?
Also i know that I must do catch (FileNotFoundExceptionex) but I don't understand why I have this error.

It does:
public void test() {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader("E:\\Users\\myFile.txt");
br = new BufferedReader(fr);
System.out.println("OK");
} catch (IOException e) {
System.out.println("Caught in try.");
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
System.out.println("Caught in catch.");
ex.printStackTrace();
}
}
}
prints
Caught in try.
java.io.FileNotFoundException: E:\Users\myFile.txt (The system cannot find the path specified) ...
BTW: You can use try with resources for a much more effective and tidy solution.
public void test() {
try (BufferedReader br = new BufferedReader(new FileReader("E:\\Users\\myFile.txt"))){
System.out.println("OK");
} catch (IOException e) {
System.out.println("Caught in try.");
e.printStackTrace();
}
}

Related

Why are two try-catch blocks required for opening and reading a file?

I am trying to read a file but it is asking for two try-catch blocks, one for opening a file and another for reading its content. Why is this required?
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
while((line=reader.readLine())!=null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Consider using finally block for avoiding memory leaks and closing the streams if you are using versions before 7. From Java 7 on wards you can use try with resources is the best practice
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try-with-Resources:
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
try(BufferedReader reader = new BufferedReader(new FileReader(file));) {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Try java8, you will not require anything. You can simply do it like this.
import java.nio.file.Files;
import java.nio.file.Paths;
Files.lines(Paths.get(path))
.filter(l -> l.contains(searchWord)).forEach(System.out::println);
The try-catch block is required for IOException.
It will check for the contents available in the file. If there are no contents, then IOException would be thrown else the contents will be displayed.
It should be like:
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
while((line=reader.readLine())!=null)
{
System.out.println(line);
}
} catch(IOException ex)
{
System.out.println(ex.getMessage());
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Improper_Restriction_of_XXE_REF

I'm new to using the Checkmarx tool and just checking for security flaws in code in general. I have a method which is supposed to read from an input stream. The method works, however I am getting XXE and SSRF errors.
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(Normalizer.normalize(line, Normalizer.Form.NFD));
}
} catch (IOException e) {
LOG.error(
"********************",
e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOG.error(
******************,
e);
}
}
}
return sb.toString();
}

Java unreported exception confusing me

Hey guys I've been working on some buttons for my GUI, and I decided to implement some previous code.
However, I'm getting an error when I try to compile. In line 141 in my code (specifically, the last button) I am told that I have an unreported IOException that must be caught or declared to be thrown.
My code is below:
public void actionPerformed(ActionEvent ae) {
if ((ae.getSource() == button5) && (!connected)) {
try {
s = new Socket("127.0.0.1", 2020);
pw = new PrintWriter(s.getOutputStream(), true);
} catch (UnknownHostException uhe) {
System.out.println(uhe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
connected = true;
t = new Thread(this);
//b.setEnabled(false);
button5.setLabel("Disconnect");
t.start();
} else if ((ae.getSource() == button5) && (connected)) {
connected = false;
try {
s.close(); //no buffering so, ok
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
//System.exit(0);
button5.setLabel("Connect");
} else {
temp = tf.getText();
pw.println(temp);
tf.setText("");
}
if (ae.getActionCommand().equals("Save it")) {
Scanner scan = new Scanner(System.in);
try {
PrintWriter pw = new PrintWriter(new FileWriter(new File("test.txt")));
for (;;) {
String temp = scan.nextLine();
if (temp.equals("")) {
break;
}
pw.println(temp);
}
pw.close();
} catch (IOException ioe) {
System.out.println("IO Exception! " + ioe.getMessage());
}
} else if (ae.getActionCommand().equals("Load it")) {
Scanner scan = new Scanner(System.in);
try {
BufferedReader br = new BufferedReader(new FileReader(new File("test.txt")));
String temp = "";
while ((temp = br.readLine()) != null) {
System.out.println(temp);
}
br.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Input file not found.");
} catch (IOException ioe) {
System.out.println("IO Exception! " + ioe.getMessage());
}
} else if (ae.getActionCommand().equals("Clear it")) {
ta.setText("");
} else {
PrintWriter pw = new PrintWriter(new FileWriter(new File("test.txt")));
}
}
just add a try/catch block to the following code (end of what you posted):
else{
PrintWriter pw = new PrintWriter (
new FileWriter(
new File("test.txt")));
}}
like so:
else{
try{
PrintWriter pw = new PrintWriter (new FileWriter(new File("test.txt")));
} catch (Exception e) {
e.printStackTrace();
}
}}
In general, any IO operation can potentially cause an exception. Depending on what you want, the easiest solution is just put throws IOException at the top of the method where you see the problem, but this isn't very good practice, and doesn't work in this case. Putting a try/catch block around the problem line, and including a meaningful error message, is probably the best way to go.

closing FileInputStream object throws exception

When I want to close InputFileStream and OutputFileStream objects, eclipse says that I need to catch IOException so here is my code after catching those exceptions.
As you can see I am catching IOException twice. Is there a more simple way that I can have only one block for catching IOException for both in.close() and in.read() ?
public class ByteStream {
public static void main(String[] args) {
FileInputStream in = null;
try {
in = new FileInputStream("testdata.txt");
int nextByte;
while((nextByte = in.read()) != -1){
System.out.println(nextByte + "-");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Use the try-with-resources syntax in Java 7
try (FileInputStream in = new FileInputStream("testdata.txt");){
int nextByte;
while ((nextByte = in.read()) != -1) {
System.out.println(nextByte + "-");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
the compiler will take care of converting the above code to code that closes the in InputStream, or any other AutoCloseable object declared and instatiated in the () part of the try expression.

Null pointer when Reading text file in java

I got Null pointer exception when reading data from file.if its returning a junk value how to handle that. if i didn't give trim giving some junk value.
My code is:
BufferedReader br = null;
try {
String sCurrentval = "";
br = new BufferedReader(new FileReader("filepath"));
while ((sCurrentval = br.readLine()) != null) {
System.out.println("Reading from File "+sCurrentval);
}
if(sCurrentval != null){
sCurrentval = sCurrentval.trim();
}
System.out.println("outside : Reading from File "+sCurrentval);
if(sCurrentval != null && !sCurrentval.equalsIgnorecase("")){
try{
val = Integer.parseInt(sCurrentval.trim());
}catch(Exception e){
e.printStackTrace();
}
}else{
System.out.println("Reading Value null ");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Your BufferedReader br = null; with in the try. But your finally also using the same variable br.
try
{
//
BufferedReader br = null; // declared with in try
//
}
finally {
try {
if (br != null) // In this line the br is not identified
br.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
Try to declare the BufferReader outside the try
BufferedReader br = null;
And then your while loop is only for the printing the value of the variable. Include the below if else condition within the while and then try the below code.
while ((sCurrentval = br.readLine()) != null)
{
System.out.println("Reading from File " + sCurrentval);
if (sCurrentval != null && !sCurrentval.trim().isEmpty())
{
try
{
val = Integer.parseInt(sCurrentval.trim());
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("Reading Value null ");
}
}

Categories

Resources