File created by try instruction? - java

try(ObjectOutPutStream utfil = new ObjectOutPutStream
(new FileOutputStream("src/eierliste.data")))
Does this instruction create the file for me, or do I have to manually create the file?
Where is src located? Which folder? What does that mean: "src/eierliste.data"

This is a new syntax present since Java 7, it's called try-with-resources. It's a shortcut to ensure that the resource opened within the try is closed automatically when the block ends, what you'd normally do in a finally block. Quoting the tutorial, this:
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
… is equivalent to this:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null)
br.close();
}
Now regarding the code in the question: it's creating a new file only if it didn't exist before (see this answer), and it's opening an ObjectOutPutStream for writing to it.

Related

Insert into a specific row using CSVwriter in java [duplicate]

This is code i Have written instead of editing a particular line new name gets appened at the last...
please help me out....
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("d:\\book.txt", true)));
BufferedReader br = null;
FileReader reader = null;
try {
reader = new FileReader("d:\\book.txt");
br = new BufferedReader(reader);
String line;
System.out.println((";;;;;;;;;;;;;;;;" + request
.getParameter("hname")));
System.out.println(request.getParameter("book"));
while ((line = br.readLine()) != null) {
if (request.getParameter("hname").equals(line)) {
line = line.replace(request.getParameter("hname"),
request.getParameter("book"));
writer.println(line);
writer.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
reader.close();
}
Unless you aren't changing the (byte) length of the line, you need to rewrite the whole file, adding the changed line where appropriate. This is actually just a simple change from your current code. First, initialize your FileWriter without the append (since you don't want to just append to the end of the file, which is what you're doing now).
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.txt")));
Then, either read the whole file into memory (if the file is small enough) or else write a temp file as you go and then copy it over when you're done. The second way is more robust, and requires less code changing; just modify your while loop to write every line, modified or not.
// Open a temporary file to write to.
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.temp")));
// ... then inside your loop ...
while ((line = br.readLine()) != null) {
if (request.getParameter("hname").equals(line)) {
line = line.replace(request.getParameter("hname"),
request.getParameter("book"));
}
// Always write the line, whether you changed it or not.
writer.println(line);
}
// ... and finally ...
File realName = new File("d:\\book.txt");
realName.delete(); // remove the old file
new File("d:\\book.temp").renameTo(realName); // Rename temp file
Don't forget to close all your file handles when you're done!

Java IO, are these resources automatically closed?

In this code I read a text file, when BufferedReader is closed by "try-resource" block so the InputStreamReader does, then can I guarantee all the resources are closed like this?
try(final BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream(file), charset))) {
String line = null;
while((line = br.readLine()) != null) {
builder.append(line);
}
}
In this other example, I write a text file, as is written, are all the resources closed in the end? Is it mandatory to call flush()?
try(final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(file), charset))) {
bw.write(text);
bw.flush();
}
Yes, the outermost streams call their inner streams' close() methods, so you only need to call the outermost stream.
You don't need to call flush(), the streams will flush when necessary and before being closed. Remove that and the code will look perfect.

File Reading in Java, with same file readers

I have two files to be read using same variables for the task with the following code:
try {
FileInputStream fis = new FileInputStream(filename1);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader br = new BufferedReader(isr);
String line="";
while((line=br.readLine())!=null){
System.out.println(line);
}
// Do i need to add these 3 statements ...
//br.close();
//isr.close();
//fis.close();
//Without the above 3 statements also the code works fine ...
fis = new FileInputStream(filename2);
isr = new InputStreamReader(fis, "UTF8");
br = new BufferedReader(isr);
line="";
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
isr.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
The filereading in java doesn't bother about closing the opened stream and releasing any system resources associated with it for the first file filename1?
No exceptions thrown.
So you have a resource leak which won't cause a problem for you unless you;
attempt to delete the file on Windows (as the file is still open)
do this many times in which case you might run out of file handles.
The code works, but it is not a good practice.
Java will automatically close the first file when the garbage collector decides to run and to deallocate your first FileInputStream object. This might happen at any time after you lose the last reference to the object, but might even not happen at all, depending on your memory conditions.
If you are using Java 7, you can use the try with resources construct, which will call close for you:
try (FileInputStream fis = new FileInputStream(filename1);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader br = new BufferedReader(isr)) {
// Code...
}
Once you created new instance for the StreamReader, Automatically call the garbage collection for the previously opened stream.

I want to open a text file and edit a specific line in java

This is code i Have written instead of editing a particular line new name gets appened at the last...
please help me out....
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("d:\\book.txt", true)));
BufferedReader br = null;
FileReader reader = null;
try {
reader = new FileReader("d:\\book.txt");
br = new BufferedReader(reader);
String line;
System.out.println((";;;;;;;;;;;;;;;;" + request
.getParameter("hname")));
System.out.println(request.getParameter("book"));
while ((line = br.readLine()) != null) {
if (request.getParameter("hname").equals(line)) {
line = line.replace(request.getParameter("hname"),
request.getParameter("book"));
writer.println(line);
writer.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
reader.close();
}
Unless you aren't changing the (byte) length of the line, you need to rewrite the whole file, adding the changed line where appropriate. This is actually just a simple change from your current code. First, initialize your FileWriter without the append (since you don't want to just append to the end of the file, which is what you're doing now).
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.txt")));
Then, either read the whole file into memory (if the file is small enough) or else write a temp file as you go and then copy it over when you're done. The second way is more robust, and requires less code changing; just modify your while loop to write every line, modified or not.
// Open a temporary file to write to.
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.temp")));
// ... then inside your loop ...
while ((line = br.readLine()) != null) {
if (request.getParameter("hname").equals(line)) {
line = line.replace(request.getParameter("hname"),
request.getParameter("book"));
}
// Always write the line, whether you changed it or not.
writer.println(line);
}
// ... and finally ...
File realName = new File("d:\\book.txt");
realName.delete(); // remove the old file
new File("d:\\book.temp").renameTo(realName); // Rename temp file
Don't forget to close all your file handles when you're done!

Cannot delete file Java

I have this method that gets the last line of a .txt file and creates a new temp file without that line. But when I try to delete the .txt that has the line I want to delete (so then I can rename the temp file) for some reason I can't. This is the code:
void removeFromLocal() throws IOException {
String lineToRemove = getLastLine();
File inputFile = new File("nexLog.txt");
File tempFile = new File("TempnexLog.txt");
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
int i = 0;
while ((currentLine = reader.readLine()) != null) {
i++;
String trimmedLine = currentLine.trim();
if (!trimmedLine.equals(lineToRemove)) {
if (i != 1) {
writer.newLine();
}
writer.write(currentLine);
}
}
reader.close();
reader = null;
writer.flush();
writer.close();
writer = null;
System.gc();
inputFile.setWritable(true);
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inputFile)) {
System.out.println("Could not rename file");
}
//boolean successful = tempFile.renameTo(inputFile);
} catch (IOException ex) {
Logger.getLogger(dropLog.class.getName()).log(Level.SEVERE, null, ex);
}
}
Whats funny is that when I press the button that calls the method once, nothing happens ("Could not delete file"), the second time it works fine and the 3rd I get "Could not rename file".
The file cannot be deleted when it's been opened by another process. E.g. in notepad or so or maybe even another FileReader/FileWriter on the file somewhere else in your code. Also, when you're executing this inside an IDE, you'll risk that the IDE will touch the file during the background scan for modifications in the project's folder. Rather store the files in an absolute path outside the IDE's project.
Also, the code flow of opening and closing the files has to be modified so that the close is performed in the finally block. The idiom is like this:
Reader reader = null;
try {
reader = new SomeReader(file);
// ...
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
Or, if you're already on Java 7, use the automatic resource management instead.
try (Reader reader = new SomeReader(file)) {
// ...
}
Further I recommend to use File#createTempFile() instead to create temp files. This way an unique temp filename will be generated and thus you prevent the very same temp file being written and renamed by multiple processes.
File tempFile = File.createTempFile("nexLog", ".txt");
Does BufferedReader close the nested reader (not mentioned in the doc)? You have to make sure, by checking if setWritable was successful.Otherwise you need to close FileReader too, and I would recommend because in case you close it twice there is no harm... by the way GC call is more harmful than useful.

Categories