Write file in linux with java isn't working - java

a java code i've been working in Windows worked perfectly, but when i tried to run it in linux didn't work (i.e it didn't create the file and therefore didn't write)...these are the functions i'm using:
BufferedWriter writer =null;//
String directory= "folder/";
java.io.File directory1 = new File(directory+"resultado");
String directory2;
directory1.mkdirs();
directory2=directory+"resultado/";
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(directory2+"resultado.txt"), "utf-8"));
writer.write("something");
writer.newLine();
} catch (IOException ex) {
System.out.println("ERRORR!!!!");
ex.printStackTrace() ;
// report
} finally {
try {writer.close();} catch (Exception ex) {//ignore}
}
}
Even thoug i have the catch IOException to write "Error" it gives me the error
Exception in thread "main" java.lang.NullPointerException
at memoria.bosques.imprimirenarchivos(bosques.java:17281)
at memoria.bosques.main2(bosques.java:18096)
at memoria.bosques.main(bosques.java:18139)
The folder of the directory is created, but it seems the functions don't create a file to write on it...what can i do?

I suggest writer is null in your finally block, because you got a prior exception, which you didn't tell us about. Either test it for null before closing, or use try-with-resources.
And when you get an exception, don't just print out "ERROR!!!!". It's useless. Print the exception.
And when you call a method like mkdirs() that returns a result, don't ignore it.

Related

How to check whether data is written in csv file using Java?

I am trying to write data into a CSV file using Spring Boot controller. But the data is not written the file.
I've tried with debugging but I couldn't find out which attribute I should look for.
When debugging, I noticed in Stream Encoder,
isOpen = true, writebuffer = null, ch = null, haveLeftoverChar = false, leftoverChar = '\u0000' 0, lcb = null
I got my data which I wished to get, perfectly right.
Here is my code:
FileWriter pw=null;
try {
pw = new FileWriter("C:\\Users\\hp\\Desktop\\all\\engine\\src\\main\\resources\\cases.csv", true);
} catch (IOException e) {
e.printStackTrace();
}
try {
pw.write("Registration Number: " + studentCase.getRegistrationNumber());
} catch (IOException e) {
e.printStackTrace();
}
try {
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
Do I have any mistakes in my controller code? and which attribute I should check to get to know whether the data is being written to the file or not?
Thanks in advance!
Do I have any mistakes in my controller code?
Yes
Your horrendous exception handling. Do not catch exceptions, then proceed as-if nothing went wrong. Something is likely going wrong and you're ignoring it.
If you check the output from the e.printStackTrace() calls, you will likely see that, but do you even know where that output goes?
Also, you should use try-with-resources. It was added in Java 7, so nobody should write code like that, not using it.
On a side note, you don't need to call flush(), since the close() method will do that for you.
So try this:
String filename = "C:\\Users\\hp\\Desktop\\all\\engine\\src\\main\\resources\\cases.csv";
try (FileWriter pw = new FileWriter(filename, true)) {
pw.write("Registration Number: " + studentCase.getRegistrationNumber());
}
Then add throws IOException to the Spring MVC controller method.
Oh, and there is no need to check if something was written. If the code reaches the next statement after the end of the try block, then something was written. That is now guaranteed, since you no longer ignore exceptions.

Java - I can't write a string to a file if the string begins with "<"

If I use the following code:
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "utf-8"));
writer.write("<title>");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
writer.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
nothing shows up in the file, but if I remove the "<" , and try to output "title>" it works fine. How can I get around this?
The problem isn't in your code, it's in the viewer (editor) that you're using to view the output. Instead of showing you the plain plain text, it's interpreting the data in the file, and showing you its interpretation. Use a plain editor such as notepad or vi to see what is in the file.
Try flushing your writer after you write:
writer.write("<title>");
writer.flush();

How to close file in Java and/or know where in my code some file is locked?

Apparently I am always calling FileReader#close() and FileWriter#close(), but some of my files remained locked by my own code.
How to
1) close file fully?
2) check, where in the code it was opened and not closed?
The question is vague and is missing context, so it makes it difficult to answer and encourages assumptions, never a good place to start from...
However, if you are doing something similar to...
try {
FileReader fr = new FileReader(new File("..."));
// Read file...
fr.close();
} catch (IOException exp) {
exp.printStackTrace();
}
Then if an exception occurs for some reason (or the code returns before it reaches the close statement), then close will never be called...
Prior to Java 7, one would typically do something like...
FileReader fr = nulll;
try {
fr = new FileReader(new File("..."));
// Read file...
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
// Avoid NullPointerException's
if (fr != null) {
fr.close();
}
} catch (Exception exp) {
}
}
This ensures that regardless of what happens between the try-catch, finally will always be called and you can take steps to ensure that the resource is closed.
With Java 7, you can now take advantage of the "try-with-resources" feature...
try (FileReader fr = new FileReader(new File("..."))) {
fr = ;
// Read file...
} catch (IOException exp) {
exp.printStackTrace();
}
Which is basically a short-cutted version of the try-catch-finally example block.
If you are using the FileLock functionality, then you also need to ensure that you releasing the FileLock when you are done with, in a similar fashion to the try-catch-finally example above, but file locking will only ensure that different processes can't read/write the simultaneously, it doesn't protect you against multiple threaded access...

Writing to Text File [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
So I'm using this function to write to text file, but the text file always ends up empty after executing. Can anyone see what the error might be? I've been stuck on this for a while.
public static void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
}
Just change your to include writer.close(); as given below
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.close();
}
//remaining code
The reason your data not saved in the file because , The Data is saved only if you call writer.flush(); And calling the writer.flush() method is enough to just save data. But you need to close the BufferedWriter() like writer.close(); to avoid resource leak. The close() calls flush() method for you before closing the stream.
After writing your output you should make sure to flush and close the socket, specially because you are using a buffered output.
writer.write(s);
writer.flush();
writer.close();
If you don't do that, the BufferedWriter will wait for additional data, but there does come none and the program execution is stopped suddenly. Using flush here is optional, as when closing it the flush is implicit, but personally I call it everytime I need to be sure that something goes out. Just like when on the toilet ;)
When you use a Buffer to write something, you must close him when you re end
writer.close();
Without closing bufferwriter you cannot see output on text file
try to add this code
writer.close()

Java File Handling, what did I do wrong?

Wrote up a basic file handler for a Java Homework assignment, and when I got the assignment back I had some notes about failing to catch a few instances:
Buffer from file could have been null.
File was not found
File stream wasn't closed
Here is the block of code that is used for opening a file:
/**
* Create a Filestream, Buffer, and a String to store the Buffer.
*/
FileInputStream fin = null;
BufferedReader buffRead = null;
String loadedString = null;
/** Try to open the file from user input */
try
{
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
fin.close();
}
/** Catch the error if we can't open the file */
catch(IOException e)
{
System.err.println("CRITICAL: Unable to open text file!");
System.err.println("Exiting!");
System.exit(-1);
}
The one comment I had from him was that fin.close(); needed to be in a finally block, which I did not have at all. But I thought that the way I have created the try/catch it would have prevented an issue with the file not opening.
Let me be clear on a few things: This is not for a current assignment (not trying to get someone to do my own work), I have already created my project and have been graded on it. I did not fully understand my Professor's reasoning myself. Finally, I do not have a lot of Java experience, so I was a little confused why my catch wasn't good enough.
Buffer from file could have been null.
The file may be empty. That is, end-of-file is reach upon opening the file. loadedString = buffRead.readLine() would then have returned null.
Perhaps you should have fixed this by adding something like if (loadedString == null) loadedString = "";
File was not found
As explained in the documentation of the constructor of FileInputStream(String) it may throw a FileNotFoundException. You do catch this in your IOException clause (since FileNotFoundException is an IOException), so it's fine, but you could perhaps have done:
} catch (FileNotFoundException fnfe) {
System.err.println("File not fonud!");
} catch (IOException ioex {
System.err.println("Some other error");
}
File stream wasn't closed
You do call fin.close() which in normal circumstances closes the file stream. Perhaps he means that it's not always closed. The readLine could potentially throw an IOException in which case the close() is skipped. That's the reason for having it in a finally clause (which makes sure it gets called no matter what happens in the try-block. (*)
(*) As #mmyers correctly points out, putting the close() in a finally block will actually not be sufficient since you call System.exit(-1) in the catch-block. If that really is the desired behavior, you could set an error flag in the catch-clause, and exit after the finally-clause if this flag is set.
But what if your program threw an exception on the second or third line of your try block?
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
By this point, a filehandle has been opened and assigned to fin. You could trap the exception but the filehandle would remain open.
You'll want to move the fin.close() statement to a finally block:
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e2) {
}
}
Say buffRead.readLine() throws an exception, will your FileInputStream ever be closed, or will that line be skipped? The purpose of a finally block is that even in exceptional circumastances, the code in the finally block will execute.
There are a lot of other errors which may happen other than opening the file.
In the end you may end up with a fin which is defined or not which you have to protect against null pointer errors, and do not forget that closing the file can throw a new exception.
My advice is to capture this in a separate routine and let the IOExceptions fly out of it :
something like
private String readFile() throws IOException {
String s;
try {
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
s = buffRead.readLine();
fin.close();
} finally {
if (fin != null {
fin.close()
}
}
return s
}
and then where you need it :
try {
loadedString = readFile();
} catch (IOException e) {
// handle issue gracefully
}

Categories