Read and write to file, but overwrites the file - java

I'm trying to figure out why this doesn't work. All the files which are shown actually exist. The 'logging.toString()' is a .txt file and it reads all the text in the logging and writes it back with the String which I want to be added. Although when I do this, it overwrites it. But I dont want that. Help?
try{
FileWriter fstream = new FileWriter(logging.toString());
BufferedWriter out = new BufferedWriter(fstream);
FileInputStream fstreams = new FileInputStream(logging);
BufferedReader br = new BufferedReader(new InputStreamReader(fstreams));
String strLine;
while ((strLine = br.readLine()) != null){
htmlTextArea = htmlTextArea + strLine + "\n";
}
out.write(htmlTextArea + logto);
out.close();
} catch (Exception ex){}

Why wouldn't it? You don't pass an append flag:
FileWriter(String filename, boolean append)
The API docs are your friend; they're often helpful for understanding behavior.

Change this line
FileWriter fstream = new FileWriter(logging.toString());
to
FileWriter fstream = new FileWriter(logging.toString(), true);
That way, you tell Java you wish to APPEND the file. There's more in the Javadocs for FileWriter.

Because that's the way FileWriter is implemented.
If you want to append, you should use a different constructor: new FileWriter( logging.toString(), true );

If you want to add something to file but not overwrite it use
FileWriter fstream = new FileWriter(logging.toString(),true);

Related

How to create and output to files in Java

My current problems lie with the fact that no matter what solution I attempt at creating a file in Java, the file never, ever is created or shows up.
I've searched StackOverflow for solutions and tried many, many different pieces of code all to no avail. I've tried using BufferedWriter, PrintWriter, FileWriter, wrapped in try and catch and thrown IOExceptions, and none of it seems to be working. For every field that requires a path, I've tried both the name of the file alone and the name of the file in a path. Nothing works.
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
I don't get any errors thrown whenever I've run my past code, however, the files never actually show up. How can I fix this?
Thank you in advance!
There are several ways to do this:
Write with BufferedWriter:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
If you want to append to a file:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
Using PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Using FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Note:
If you try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown.
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it.
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream.
Source and More Examples: https://www.baeldung.com/java-write-to-file
Hope this helps. Good luck.
A couple of things worth trying:
1) In case you haven't (it's not in the code you've shown) make sure you close the file after you're done with it
2) Use a File instead of a String. This will let you double check where the file is being created
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
As a bonus, Java's try-with-resource will automatically close the resource when it's done, you might want to try
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}

How to write data to file on starting

I am using below code to write data in a file.
public static void writeDataToFile(final String fileName, final String fileContents) {
try {
File file = new File(Environment.getExternalStorageDirectory() + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(fileContents);
writer.flush();
writer.close();
} catch (IOException e) {
LogUtility.logInfo(TAG, e.getMessage());
}
}
Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help
You can set the append flag to false in the FileWriter constructor. Then, use the write() function instead of the append() function
FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);
Why don't you remove the file if it exists:
if (!file.exists()) {
file.createNewFile();
} else {
file.delete()
file.createNewFile();
}
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one
Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.
StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
file.createNewFile();
} else {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = bufferedReader.readLine();
}
contentToWrite.append("\n\n" + sb);
file.delete();
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();
PS: Don't forget to close FileReader and BufferedReader in a finally statement.

Having problems with removing first line from txt file

I know this is very basic stuff but for some reason I'm having problems with a bufferedReader/ Writer. I am trying to get the first line of text and return it to another method. However, for some reason the writer doesn't seem to be writing to the temp file and it isn't changing the name of the temp file either.
By throwing a few print statements I have been able to figure out:
The while loop is operating correctly
The if else statement is operating correctly
The tempFile is not writing to a text file correctly
The tempFile is not renaming correctly
There are no errors being thrown
private static String wavFinder() throws IOException{
String currentWav=null;
int x = 1;
File inputFile = new File("C:\\convoLists/unTranscribed.txt");
File tempFile = new File("C:\\convoLists/unTranscribedtemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine = null;
while((currentLine = reader.readLine()) != null) {
if(x == 1){
currentWav = currentLine;
}
else{
writer.write(currentLine);
}
x = 2;
}
boolean successful = tempFile.renameTo(inputFile);
System.out.println("Success: " + successful);
System.out.println("currentWav = " + currentWav);
return currentWav;
}
Here is the method I am using. If you notice anything please let me know and if you have any questions I will be sure to answer them quickly. Thank you :)
First flush the steam(writer) and close them.
You can not have two files with same name. You are trying to rename the temp file with input file. You need to delete input file and then rename it to that.
reader.close();
writer.flush();
writer.close();
inputFile.delete();
Add these lines before rename and it will work
Close your buffers before trying to call renameTo.
reader.close()
writer.close()
File inputFile = new File("C:\convoLists/unTranscribed.txt");
File tempFile = new File("C:\convoLists/unTranscribedtemp.txt");
Why you have different signs for path?
Always should be //.

How to append a new line to beginning of an existing file in java?

Assuming I have a txt file located in /mypath/sampletext.txt. How do I append a new line to the beginning of the file with the following in Java while preserving the original text file's contents?:
String startStr ="--Start of File--";
Looking for a way to do this without having to create an intermediary 2nd file and make modifications only to the existing file if possible.
Read file contents first, prepend new line to that like contents = newLine + contents, then write the new conent in the same file (dont append).
well,three ways ,may help you
1.
//true: is append text to fie
FileWriter write = new FileWriter("file_path",true);
writer.write(content);
//open randomFile and "rw"
randomFile = new RandomAccessFile("file_path", "rw");
// file length
long fileLength = randomFile.length();
//point to end index
randomFile.seek(fileLength);
//write
randomFile.writeBytes(content);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(conent);
New answer is updated...
In this I've use few more FileIO classes & may be their one is deprecated API but If you are aware with Java FileIO classes you can easily fix it.
Here I append new line at the start of file rather than append it to the end of file..
If any issue please comment again....
Try this, I think it will help you..
try
{
//Append new line in existing file.
FileInputStream fr = new FileInputStream("onlineSoultion.txt");
DataInputStream dr = new DataInputStream(fr);
String startStr = "--Start of File--\n";
//String startStr;
while (dr.available() > 0) {
startStr += dr.readLine();
//System.out.println(startStr);
}
dr.close();
fr.close();
FileOutputStream writer = new FileOutputStream("onlineSoultion.txt");
writer.write((new String()).getBytes());
writer.close();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("onlineSoultion.txt", true)));
out.println(startStr);
out.close();
}

How to delete a specific string in a text file?

How can I delete a specific string in a text file?
Locate the file.
File file = new File("/path/to/file.txt");
Create a temporary file (otherwise you've to read everything into Java's memory first).
File temp = File.createTempFile("file", ".txt", file.getParentFile());
Determine the charset.
String charset = "UTF-8";
Determine the string you'd like to delete.
String delete = "foo";
Open the file for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
Open the temp file for writing.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
Read the file line by line.
for (String line; (line = reader.readLine()) != null;) {
// ...
}
Delete the string from the line.
line = line.replace(delete, "");
Write it to temp file.
writer.println(line);
Close the reader and writer (preferably in the finally block).
reader.close();
writer.close();
Delete the file.
file.delete();
Rename the temp file.
temp.renameTo(file);
See also:
The Java Tutorials - Lesson: basic I/O

Categories

Resources