I want to edit part of a line in a text file - java

BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("Smokey")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\n");
} else {
bw.write(line+"\n");
}
}
}
catch (Exception e) {
return;
} finally {
try {
if(br != null){
br.close();
messagejLabel.setText("Error");
}
} catch (IOException e) {
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
When running the code above I end up with an empty file "tmpfiles.txt" and the file "files.txt is being deleted. can anyone help? I don't want to use a string to read the file. I would prefer to do it his way.

A quick test confirmed that not closing the writer as I wrote in my comment above actually produces the behavior you describe.
Just add
if (bw != null) {
bw.close();
}
to your finally block, and your program works.

I found some issue in your code.
First, this line seems not correct:
if (line.contains("Smokey")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\n");
it should be:
if (line.contains("Smokey;")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\r\n");
And, you should flush and close the bw after finish it.
if (bw != null){
bw.flush();
bw.close();
}
Correct me if I'm wrong.

The file is never written to because the writer was never "flushed". When closing the writer all the data in the buffer is automatically written to the file. Get used to standards with streams where you close them in a try-catch block.

Related

Why won't my lambda write to the .txt files it creates?

I have an AWS lambda program written in Java that is supposed to create a bunch of txt files then write URLs to them and move them to a bucket. It appears to be creating the .txt files in the /tmp/ folder of the lambda but not writing anything to them, because I keep getting FL2: null. The bucket gets .txt files with the right names but they're empty.
The FileNames are all of the format "/tmp/[name].txt". The map has txt filenames followed by a list of URLs. The buffered reader was simply my own code to see if it could read the .txts that were created.
for (Map.Entry<String, ArrayList<String>> entry: files.entrySet()) {
String fileName = entry.getKey();
ArrayList<String> list = entry.getValue();
File file = new File(fileName);
FileWriter writer = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
if (!file.exists()){
log.info("It doesn't exist as a temp.");
if( !file.createNewFile()){
log.error(fileName+" not created. Skipping");
continue;
}
}
writer = new FileWriter(file, StandardCharsets.UTF_8);
bw = new BufferedWriter(writer);
for (int i=0; i< list.size(); i++) {
String url = list.get(i);
log.info("Inserting " + url + " into file " + fileName);
if (i !=0){
bw.write("\n");
}
bw.write(url);
}
br = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
log.info("FL2: "+br.readLine());
String key = fileName.substring(5);
amazonS3.putObject("[bucketname]", key, file);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if (writer != null) {
writer.close();
}
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("End of the sitemap generator");
}
I tried the above code, and I tried printWriter turning into a bufferedWriter.
Your code is writing to the text file and later reading from the same text file. But ... your code doesn't close the writer until the finally section of code so the read happens before the writer closes and consequently the written data, which is buffered, has not been flushed to disk.
The fix is to close the buffered writer before reading from the same file.
Also, you can reduce the amount of state in your program as follows, while also reducing the number of closes you have to do:
BufferedWriter bw = new BufferedWriter(new FileWriter(file, ...));
You might also consider using try-with-resources to auto flush/close your files.

Add Text To An Existing Text File

Hello I am new to Android development. I am developing an app as a training. So now my target is to add some new text to an existing text file.
For example: I have a text file in "sdCard/android.txt" and in this file there are some data written "I love android". Now I want to add some more texts "It is awesome" in a new line of that file.
Finally the android.txt ahould look like this:
I love android
It is awesome
So how can I achieve that?
You can just do it as you do it in Java.
try {
String fn = getExternalFilesDir(null) + File.separator + "android.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fn, true));
bw.write("\nIt is awesome\n");
bw.close();
// checking
BufferedReader br = new BufferedReader(new FileReader(fn));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
You can look at this example and use a BufferedWriter. When you execute File-Read or -Write operations, make sure to always use try/catch blocks.
public void appendText () {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Path-to-your-file", true));
bw.write("text-to-append");
bw.newLine();
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
You should definitely read about IO (Input-Output) Operations in Android/Java. https://docs.oracle.com/javase/tutorial/essential/io/
Good luck!

Cannot rename temp.txt to original.txt after removing line

I have the following code I've placed into a custom method.
File inputFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\original.txt"); // Your file
File tempFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\temp.txt");// temp file
BufferedReader reader = null;
BufferedWriter writer = null;
try{
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile));
String firstName = chosenEmployee.getFirstName();
String lastName = chosenEmployee.getLastName();
String currentLine;
while((currentLine = reader.readLine()) != null) {
if(currentLine.contains(firstName)
&& currentLine.contains(lastName)) continue;
writer.write(currentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}finally{
try {
inputFile.delete();
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
} catch (IOException ex) {
ex.printStackTrace();
}
}
The problem is; whenever I run the program the renameTo fails; but it does create a temp.txt with the line that was supposed to be removed correctly removed.
Why does renameTo always return false though?
Edit 1: The files are not opened anywhere else in windows. They are listed in my IDE's project explorer but are not opened by my IDE.
The javadoc for renameTo() says:
The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists.
Try closing all the files (you are not closing reader so it is still "in use") and deleting first the input file:
} finally {
try {
inputFile.delete();
reader.close();
writer.close();
inputFile.delete();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
} catch (IOException ex) {
ex.printStackTrace();
}
}

Still resource leak after closing BufferedReader

I'm still learning Java and I need some help understanding why this code is wrong:
BufferedReader infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
infile.close();
I really don't see the problem but Eclipse keeps telling there is a resource leak and that infile isn't closed.
(one more detail, this code stands in a try block but I left it away to keep it simple)
Eclipse is complaining because the reference may not be closed (for example, in an Exception); this is where you would use a finally block - perhaps like so
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
} catch (Exception e) {
e.printStackTrace(); // Log the exception.
} finally {
if (infile != null) {
infile.close(); // close the resource.
}
}
You should have a try/catch block.
Also you should use the following instead:
while ((line = reader.readLine()) != null) {
//do something with line;
}
I think Elliott Frisch is correct and pointed out the main reason the only thing I would add is You should close the stream (in a finally block) because to ensure that any output buffers are flushed in the case that output was otherwise successful. If the flush fails, the code should exit via an exception. Here is another example similar to what you are trying to solve and make sure you look at (Guideline 1-2: Release resources in all cases) http://www.oracle.com/technetwork/java/seccodeguide-139067.html
final OutputStream rawOut = new FileOutputStream(file);
try {
final BufferedOutputStream out =
new BufferedOutputStream(rawOut);
use(out);
out.flush();
} finally {
rawOut.close();
}

Android: Append to file instead of ovewriting

I am trying to append to a text file but for some reason it keeps overwriting it, here's my code:
File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt");
try {
if(!logFile.exists()) {
logFile.createNewFile();
}
StringBuilder text = new StringBuilder(); // build the string
String line;
BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file
while ((line = br.readLine()) != null) { // if not empty continue
text.append(line);
text.append('\n');
}
BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
output.write(text + "\n");
output.close();
alertDialog.show();
} catch (IOException ex) {
System.out.println(ex);
}
thank you in advance
use
new FileWriter(logFile, true)
Where the second parameter tells it to append, not overwrite.
Found in this question. In the related questions on the right.
Documentation can be found here
You need to use the other constructor of FileWriter that specifies whether the data is overwritten or appended. Use FileWriter(logFile, true) instead of what you have now :)

Categories

Resources