I am running the following code to try and read from a text file. I am fairly new to java and have been practicing by trying to create projects for myself. The following code is slightly modified from what I originally found to try and read a text file but for some reason it catching the exception every time. The text file that it is trying to read from only says "hello world". I assume it must not be finding the text file. I put it in the same folder as the source code and it appears in the source packages (I'm using netbeans btw). It probably just needs to be imported differently but I can't find any further info on it. In case my code is relevant here it is below.
package stats.practice;
import java.io.*;
import java.util.Scanner;
public final class TextCompare {
String NewString;
public static void main() {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
System.out.println("Error");
}
}
The closing brace in the catch block is misplaced. Move it to be below the System.out.println("Error");.
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) { // <-- from here
System.out.println("Error");
// or even better
e.printStackTrace();
} // <-- to here
}
As a matter of defensive programming (pre-Java 7 at least) you should always close resources in a finally block:
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {}
}
// or if you're using Google Guava, it's much cleaner:
Closeables.closeQuietly(in);
}
}
If you are using Java 7, you can take advantage of automatic resource management via try-with-resources:
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It isn't necessarily catching the exception every time. Your System.out.println("Error"); statement is outside of the catch block. Therefore, it is executed every time the program executes.
To fix this, move it within the braces (catch (IOException e) {System.out.println("Error");})
First step, replace below code
catch (IOException e){}
with
catch ( IOException e) { e.printStackTrace(); }
and also replace
main()
with
main(String[] args)
This will tell you the exact reason. and then you have to solve the actual reason.
Now for Netbeans, the file hello.txt has to be in your Netbeans project. like
<project_dir>
|
-->hello.txt
-->build
-->src
You have an empty catch block which is almost always a bad idea. Try putting this there:
... catch (IOException ex) {
ex.printStackTrace();
}
And you should quickly see what's going on.
Related
I am working on a debuging csv output inside an event driven java application. I define my filewriter like this on init.
public File csvFile;
public FileWriter fileWriter;
then I initialies them
this.csvFile = new File("c:\\missingitems.csv");
this.fileWriter = null;
try {
this.fileWriter = new FileWriter(this.csvFile);
StringBuilder line = new StringBuilder();
line.append("Date, ItemId");
line.append("\n");
this.fileWriter.write(line.toString());
} catch (IOException e) {
e.printStackTrace();
}
then within my actual program logic this gets called for every timestep in my data
for(Long item : this.items) {
StringBuilder line = new StringBuilder();
line.append(event.getDateTime().toLocalDate().toString() + "," +item.intValue());
line.append("\n");
try {
this.fileWriter.write(line.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
on exit of my program I call
try {
this.fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
However this seems to be only working if i close the filewriter after each append. Is there a way of keeping the file open and just append to it, I would also like to not loose my data in case my application crashes. I am a python guy and not super familiar with java.
I'm trying to read ObjectOutputStream from a file and convert it to an arraylist.
This whole thing is happening inside a method which should read the file and return the array list:
public static List<Building> readFromDatabase(){
String fileName="database.txt";
FileInputStream fileIStream=null;
ObjectInputStream in=null;
List<Building> buildingsArr=null;
try
{
fileIStream = new FileInputStream(fileName);
in = new ObjectInputStream(fileIStream);
buildingsArr=(ArrayList<Building>)in.readObject();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
return buildingsArr;
}
}
Java tells me that this is dangerous.
What are the alternatives?
I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.
I need to both make sure files will be closed, and return the array list I created as well.
Any ideas?
I can't put the return in the "try" block because it won't do it / it
won't close files in the "finally" block.
Wrong, finally block would still execute if you put return in try block. Thus you can return in your try block.
try
{
//your code
return buildingsArr;
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
}
I would suggest starting to use Java 7, and the try with resources clause. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ex:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
You must either throw an Exception or return a value:
All you need to prove this is comment out the return "File Not Found" after the finally block and see that it won't compile.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReturnFinallyExample
{
public static void main(final String[] args)
{
returnFinally();
}
private static String returnFinally()
{
try
{
final File f = new File("that_does_not_exist!");
final FileInputStream fis = new FileInputStream(f);
return "File Found!";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally!");
}
return "File Not Found!";
}
}
You must have the return after the finally or you have to either:
declare the method to throws FileNotFoundExceptoin and re-throw the FileNotException out.
or
wrap the FileNotFoundException with throw new RuntimeException(e)
I am trying to do some kind of serialization where I can directly read and write objects from file.
To start of I just tried to write a character to file and tried to read it. This keeps giving me EOF exception always.
I am trying it on a Android device. Here is my code:
public class TestAppActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
WriteToFile();
Load();
} catch (Exception e) {
e.printStackTrace();
}
}
public void Load () throws IOException
{
InputStream fis;
ObjectInputStream in = null;
try {
fis = new FileInputStream(Environment.getExternalStorageDirectory() + "\\test2.ser");
in = new ObjectInputStream(fis);
char temp = in.readChar();
} catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
}
}
public static void WriteToFile() throws Exception {
try {
OutputStream file = new FileOutputStream(Environment.getExternalStorageDirectory() + "\\test2.ser");
ObjectOutput output = new ObjectOutputStream(file);
try {
output.writeChar('c');
} finally {
output.close();
}
} catch (IOException ex) {
throw ex;
}catch (Exception ex) {
throw ex;
}
}
}
In this case, EOFException means there is no more data to be read, which (again in this case) can only mean that the file is empty.
Why are you using ObjectInput/OutputStreams but only writing chars? You'd be better off with DataInput/OutputStreams for that usage.
Also there is no point in catching exceptions only to rethrow them.
Also there is no point in reading a char from a file unless you are going to put it somewhere other than in a local variable that isn't even returned by the method.
I have imported this code in my sample project with following change.
i replaced "\\test2.ser"with "/test2.ser" and it worked. please try this.
I want to close my stream in the finally block, but it throws an IOException so it seems like I have to nest another try block in my finally block in order to close the stream. Is that the right way to do it? It seems a bit clunky.
Here's the code:
public void read() {
try {
r = new BufferedReader(new InputStreamReader(address.openStream()));
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
} catch (IOException readException) {
readException.printStackTrace();
} finally {
try {
if (r!=null) r.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
Also if you're using Java 7, you can use a try-with-resources statement:
try(BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))) {
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
} catch(IOException readException) {
readException.printStackTrace();
}
It seems a bit clunky.
It is. At least java7's try with resources fixes that.
Pre java7 you can make a closeStream function that swallows it:
public void closeStream(Closeable s){
try{
if(s!=null)s.close();
}catch(IOException e){
//Log or rethrow as unchecked (like RuntimException) ;)
}
}
Or put the try...finally inside the try catch:
try{
BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()));
try{
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
}finally{
r.close();
}
}catch(IOException e){
e.printStackTrace();
}
It's more verbose and an exception in the finally will hide one in the try but it's semantically closer to the try-with-resources introduced in Java 7.
In Java 7 you can do this...
try (BufferedReader r = new BufferedReader(...)){
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
} catch(IOException e) {
//handle exception
}
Declaring a variable in the try block requires that it implements AutoCloseable.
Declaring a variable in the try block also limits its scope to the
try block.
Any variable declared in the try block will automatically have close() called when the try block exits.
It's called a Try with resources statement.
Yes it is clunky, ugly and confusing. One possible solution is to use Commons IO which offers a closeQuietly method.
There's a number of questions in the "Related" column on the right hand of this page that are actually duplicates, I advise to look through these for some other ways of dealing with this issue.
Like the answer mentioning the Commons IO library, the Google Guava Libraries has a similar helper method for things which are java.io.Closeable. The class is com.google.common.io.Closeables. The function you are looking for is similarly named as Commons IO: closeQuietly().
Or you could roll your own to close a bunch like this: Closeables.close(closeable1, closeable2, closeable3, ...) :
import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;
public class Closeables {
public Map<Closeable, Exception> close(Closeable... closeables) {
HashMap<Closeable, Exception> exceptions = null;
for (Closeable closeable : closeables) {
try {
if(closeable != null) closeable.close();
} catch (Exception e) {
if (exceptions == null) {
exceptions = new HashMap<Closeable, Exception>();
}
exceptions.put(closeable, e);
}
}
return exceptions;
}
}
And that even returns a map of any exceptions that were thrown or null if none were.
Your approach within finally is correct. If the code that you call in a finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it bubble out of the finally block.
Within the catch block you are swallowing the exception - which is not correct.
Thanks...
public void enumerateBar() throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM Bar");
// Use resultSet
}
finally {
try {
if (resultSet != null)
resultSet.close();
}
finally {
try {
if (statement != null)
statement.close();
}
finally {
connection.close();
}
}
}
}
private Connection getConnection() {
return null;
}
source.
This sample was useful for me.
First thing I noticed in your code is curly bracket { } missing from your code if you look at it. also you need to initialize value of r to null so you need to pass null value to object at first so that if condition you have written can do not null condition check and lets you close the stream.
I am using a buffered writer and my code, closes the writer in the finally block. My code is like this.
...........
BufferedWriter theBufferedWriter = null;
try{
theBufferedWriter =.....
....
......
.....
} catch (IOException anException) {
....
} finally {
try {
theBufferedWriter.close();
} catch (IOException anException) {
anException.printStackTrace();
}
}
I have to use the try catch inside the clean up code in finally as theBufferedWriter might also throw an IOException. I do not want to throw this exception to the calling methos. Is it a good practice to use a try catch in finally? If not what is the alternative? Please suggest.
Regards,
Hiral
A somewhat nicer way to do this is to use IOUtils.closeQuiety from Apache commons-io. It keeps your code tidy and eliminates some of the boilerplate that's inherent in Java.
You code then becomes:
BufferedWriter theBufferedWriter = null;
try{
theBufferedWriter = ...
...
} catch (IOException anException) {
...
} finally {
IOUtils.closeQuietly(theBufferedWriter);
}
Much nicer and more expressive.
In pre Java 7, I'd say what you have written is the best solution.
In Java 7 and onwards you have Automatic Resource Management intended to simplify these things. With this feature, you can do
BufferedWriter theBufferedWriter = null;
try (BufferedWriter theBufferedWriter = ...) {
....
......
.....
} catch (IOException anException) {
....
}
Or you can use Lombok and the #Cleanup annotation and you shall never write a try catch inside finally again.
This is how you would normally write it (Note the throws IOException):
//Vanilly Java
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(args[0]);
try {
OutputStream out = new FileOutputStream(args[1]);
try {
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
}
Now with Lombok you just write #Cleanup on the streams
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
#Cleanup InputStream in = new FileInputStream(args[0]);
#Cleanup OutputStream out = new FileOutputStream(args[1]);
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
}
}
This is what we will have to live with until Java 7 and ARM Blocks.
It's OK but you should test if theBufferedWriter is not null before closing it.
You could also do:
BufferedWriter theBufferedWriter;
try {
theBufferedWriter = new ...
try {
...
} finally {
try {
theBufferedWriter.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
} catch (IOException anException) {
...
}
or:
BufferedWriter theBufferedWriter;
try {
theBufferedWriter = new ...
} catch (IOException createException) {
// do something with createException
return; // assuming we are in a method returning void
}
try {
...
} catch (IOException anException) {
...
// assuming we don't return here
}
try {
theBufferedWriter.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
but mostly I do such operations (e.g. writing a file) in a dedicated method and prefer to throw the/an Exception so the caller can handle it (e.g. asking for another file, stopping the application, ...):
void someMethod(...) throws IOException {
BufferedWriter theBufferedWriter = new ...
try {
...
} catch (IOExcepption anException) {
try {
theBufferedWriter.close();
} catch (IOException closeException) {
closeException.printStackTrace();
// closeException is not thrown, anException represents the main/first problem
}
throw anException;
}
theBufferedWriter.close(); // throws the Exception, if any
}
Please note: English is not my first nor my second language, any help would be appreciated
It's ok to put a try-catch in a finally. It is the tool that does what you want to do. However, I feel the thrown IOException on close is uncommon enough that I would allow it to suppress any exception in the body like so.
try {
BufferedWriter writer = .....
try {
.....
} finally {
writer.close();
}
} catch (IOException e) {
....
}