I am stuck on something very basic. In our game we have a leveleditor/loader that can fetch levels via URL. Now if the URL points to a nonexistant file the editor should refuse to load the level and simply stay in its currentlevel, I am just struggling with the basic code.
private void loadLevel(URL url) {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
readLine(in);
in.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Essentially, if FileNotFound is thrown (or any other) readLine(in) should NOT proceed. All kinds of NPE if it does.
private void loadLevel(URL url) {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
/*if(in!=null){
readLine(in);
in.close();
}*/
readLine(in);
in.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT: After #LuiggiMendoza's suggestion.
Use throws and finally. Let the calling function handle it. I haven't tested it, but this sort of thing is the idea...
private void loadLevel(URL url) throws IOException, FileNotFoundException {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
if (in == null) throw new FileNotFoundException();
readLine(in);
}
finally {
in.close();
}
}
On the context of one single thread, if this line below throws exception, the next line of code will not execute. If you think your code is doing otherwise, it might be another thread doing it / some other code
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
Related
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();
}
I am trying to write to a file and then read from that same file. The output is "Error: I/O exception". Meaning that the program is catching the IOException.
public class fileIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
File file = new File("io.txt");
BufferedReader read = new BufferedReader(new FileReader(file));
BufferedWriter write = new BufferedWriter(new FileWriter(file));
String needs = "This is going to the file";
write.write(needs);
String stuff = read.readLine();
while(stuff != null)
{
System.out.println(stuff);
stuff = read.readLine();
}
}
catch(IOException e)
{
System.out.println("Error: I/O Exception");
}
catch(NullPointerException e)
{
System.out.println("Error: NullPointerException");
}
}
}'
You cannot read from and write to the file at the same time, this will throw an IOException. You should close anything that has access to the file before trying to access it with something else. Invoking the close() method on BufferedWriter before trying to access the file with BufferedReader should do the trick.
EDIT: Also, as others have mentioned, you can use e.printStackTrace() to see where an exception has occurred in your program, which greatly helps when debugging.
EDIT: As zapl clarified, this is the case for some file systems, including Windows, but not all. It was my assumption that you were using a file system that restricts this as it seemed like the most likely problem.
I moved the BufferedReader to after where I closed the the BufferedWriter and that did the trick. thanks for the help.
public class fileIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
File file = new File("io.txt");
BufferedWriter write = new BufferedWriter(new FileWriter(file));
String needs = "This is going to the file";
write.write(needs);
write.close();
BufferedReader read = new BufferedReader(new FileReader(file));
String stuff = read.readLine();
while(stuff != null)
{
System.out.println(stuff);
stuff = read.readLine();
}
read.close();
}
catch(IOException e)
{
System.out.println("Error: I/O Exception");
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("Error: NullPointerException");
e.printStackTrace();
}
}
}
I have a code snippet I am working on:
public void readFile()
{
BufferedReader reader = null;
BufferedReader reader2 = null;
try
{
reader = new BufferedReader(new FileReader("C:/Users/user/Desktop/testing.txt"));
reader2 = new BufferedReader(new FileReader("C:/Users/user/Desktop/testNotThere.txt"));
}
catch (FileNotFoundException e)
{
System.err.println("ERROR: FILE NOT FOUND!\n");
}
String line = null;
try {
while ((line = reader.readLine()) != null)
{
System.out.print(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
And while I understand what the first exception the snippet detects: catch (FileNotFoundException e), I am looking to understand what the second exception is looking for while printing the lines of the text file:
catch (IOException e)
{
e.printStackTrace();
}
Can anyone explain what this second exception is looking for? Furthermore, how can I test to make sure this exception will be thrown in the snippet like I did with creating a second BufferedReader reader2?
IOException is thrown when your program is interrupted while reading the file.
As you may see, IO stands for "Input/Output" which means reading and writing data on disk.
So an exception of that kind means that the system crashed while while doing a reading/writing.
Source: http://docs.oracle.com/javase/7/docs/api/java/io/IOException.html
I got a Follower-check function in my twitch.bot and i need a read/write solution for it.
It should do the following:
Read an given Number(int) out of the file
Write a new Number to the file and delete the old one
Create the file if it doesnt exist
(the File needs only to store 1 number)
So how can i do this?
right now, i got a String Reader and as soon as i read it i parse it into an INT but i only got errors so i think it doesnt work that way so im searching an option for writing/reading the int already without parsing it from a string.
import java.io.*;
public class FollowerChecker {
public static StringBuilder sb;
static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public static void Writer() {
FileWriter fw = null;
try {
fw = new FileWriter("donottouch.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringWriter sw = new StringWriter();
sw.write(TwitchStatus.totalfollows);
try {
fw.write(sw.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It appears to be way more complicated than it should be. If you just want to write a number without parsing it as text you can do this.
BTW You may as well use a long as it will use the same disk space and store more range.
public static void writeLong(String filename, long number) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
dos.writeLong(number);
}
}
public static long readLong(String filename, long valueIfNotFound) {
if (!new File(filename).canRead()) return valueIfNotFound;
try (DataInputStream dis = new DataInputStream(new FieInputStream(filename))) {
return dis.readLong();
} catch (IOException ignored) {
return valueIfNotFound;
}
}
I was working normally in eclipse when I got bugged by a resource leak warning in both return values inside the try block in this method:
#Override
public boolean isValid(File file) throws IOException
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null)
{
line = line.trim();
if(line.isEmpty())
continue;
if(line.startsWith("#") == false)
return false;
if(line.startsWith("#MLProperties"))
return true;
}
}
finally
{
try{reader.close();}catch(Exception e){}
}
return false;
}
I don't understand how it would cause resource leak since I'm declaring the reader variable outside the try scope, adding a resource inside the try block and closing it in a finally block using an other try...catch to ignore exceptions and a NullPointerException if reader is null for some reason...
From what I know, finally blocks are always executed when leaving the try...catch structure, so returning a value inside the try block would still execute the finally block before exiting the method...
This can be easily proved by:
public static String test()
{
String x = "a";
try
{
x = "b";
System.out.println("try block");
return x;
}
finally
{
System.out.println("finally block");
}
}
public static void main(String[] args)
{
System.out.println("calling test()");
String ret = test();
System.out.println("test() returned "+ret);
}
It result in:
calling test()
try block
finally block
test() returned b
Knowing all this, why is eclipse telling me Resource leak: 'reader' is not closed at this location if I'm closing it in my finally block?
Answer
I would just add to this answer that he's correct, if new BufferedReader throws an exception, an instance of FileReader would be open upon destruction by garbage collector because it wouldn't be assigned to any variable and the finally block would not close it because reader would be null.
This is how I fixed this possible leak:
#Override
public boolean isValid(File file) throws IOException
{
FileReader fileReader = null;
BufferedReader reader = null;
try
{
fileReader = new FileReader(file);
reader = new BufferedReader(fileReader);
String line;
while((line = reader.readLine()) != null)
{
line = line.trim();
if(line.isEmpty())
continue;
if(line.startsWith("#") == false)
return false;
if(line.startsWith("#MLProperties"))
return true;
}
}
finally
{
try{reader.close();}catch(Exception e){}
try{fileReader.close();}catch(Exception ee){}
}
return false;
}
There is technically a path for which the BufferedReader would not be closed: if reader.close() would throw an exception, because you catch the exception and do nothing with it. This can be verified by adding reader.close() again in your catch block:
} finally
{
try {
reader.close();
} catch (Exception e) {
reader.close();
}
}
Or by removing the try/catch in the finally:
} finally
{
reader.close();
}
This will make the warnings disappear.
Of course, it doesn't help you. If reader.close() is failing, then calling it again does not make sense. The thing is, the compiler is not smart enough to handle this. So the only sensible thing you can do is to add a #SuppressWarnings("resource") to the method.
Edit If you are using Java 7, what you can/should do is using try-with-resources functionality. This will get the warnings right, and makes you code simpler, saving you a finally block:
public boolean isValid(File file) throws IOException
{
try(BufferedReader reader = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = reader.readLine()) != null)
{
line = line.trim();
if (line.isEmpty())
continue;
if (line.startsWith("#") == false)
return false;
if (line.startsWith("#MLProperties"))
return true;
}
}
return false;
}
If the BufferedReader constructor throws an exception (e.g. out of memory), you will have FileReader leaked.
//If this line throws an exception, then neither the try block
//nor the finally block will execute.
//That is a good thing, since reader would be null.
BufferedReader reader = new BufferedReader(new FileReader(aFileName));
try {
//Any exception in the try block will cause the finally block to execute
String line = null;
while ( (line = reader.readLine()) != null ) {
//process the line...
}
}
finally {
//The reader object will never be null here.
//This finally is only entered after the try block is
//entered. But, it's NOT POSSIBLE to enter the try block
//with a null reader object.
reader.close();
}
Since close() can throw an exception (why oh why did they design it that way...) I tend to use a double try
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
// do stuff with reader
} finally {
reader.close();
}
} catch(IOException e) {
// handle exceptions
}
Since this idiom eliminates the try/catch within the finally block it may be enough to keep Eclipse happy.
new BufferedReader(...) can't itself throw an IOException but technically this could still leak the FileReader if the BufferedReader constructor throws a RuntimeException or Error.