Text File writing in Java - java

I am writing String content to text file in Java code but after writing saving file onto disk, I am getting Incorrect encoding exception, Please suggest me correct Java Code?
String content =fileContent;//fileContent.toString();
System.out.println("File Contt===>"+content);
File fileWrite = new File("/homeDesktop/NormalFile/"+filename);
// if file doesnt exists, then create it
if (!fileWrite.exists()) {
fileWrite.createNewFile();
}
FileWriter fw = new FileWriter(fileWrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContent);
bw.close();

IOUtils.toString(String) Converts your coding.
String not encoded in UTF-8
NOTE:
You dont need this:
// if file doesnt exists, then create it
if (!fileWrite.exists()) {
fileWrite.createNewFile();
}
File create automatically a new file, if there isn't one.

Related

FileInputStream and FileOutputStream: Read and write to the same file

I created a text file with the content "Hello" and I was trying to read these characters from the file and write it back to the same file again.
Assumptions:
1. the file now has the content "Hello" (Overwritten)
2. the file now has the content "HelloHello" (Appended)
3. the file now has the content infinite "Hello" (or an exception gets thrown)
Actual result:
Original "Hello" characters gets deleted from the text file, and the file was left empty.
Actual test
#Test
public void testCopyStream() throws IOException {
File workingDir = new File(System.getProperty("user.dir"));
File testFile = new File(workingDir, "/test.txt");
FileReader fin = new FileReader(testFile);
FileWriter fos = new FileWriter(testFile);
copyStream(fin, fos);
fin.close();
fos.close();
}
I have created the following method for "copying" the data in the InputStream to the OutputStream:
private void copyStream(Reader in, Writer out) throws IOException {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
I tried using debugger to find out the problem, and the debugger shows b = in.read() was assigned -1 at the first iteration of the while loop. Then I executed the code step by step while inspecting the file's content and found that "Hello" keyword got deleted from the file right after statementfinal FileWriter fos = new FileWriter(testFile); gets executed.
I first thought this was due to the InputStream and OutputStream were pointed to the same file so the file gets sort of "locked" by JVM for execution safety?
So I tried swapping those two lines:
FileWriter fos = new FileWriter(testFile);
FileReader fin = new FileReader(testFile);
And the result turned out the same: the file content got eliminated right after the statement FileWriter fos = new FileWriter(testFile);
My questions is: why the content gets cleaned out by FileWriter?. Is this some behavior related to FileDescriptor? Is there a way to read and write to the same file?
Just FYI,
copyStream() method is working fine, I have tested it with other tests.
It's not about using append() method instead of write()
The statement FileWriter fos = new FileWriter(testFile); truncates the existing file.
It does not make sense for you to use streaming access to read and write the same file, as this won't give reliable results. Use RandomAccessFile if you want to read / write the same file: this has calls to seek current position and perform read or writes at different positions of a file.
https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
FileWriter actually deletes everything in a file before writing. To preserve the text, use
new FileWriter(file, true);
The true parameter is the append parameter of the filewriter. Otherwise it will just overwrite everything

Java create a new file, or, override the existing file

What I want to achieve is to create a file regardless of whether the file exists or not.
I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?
Or is there a clearer way of doing it?
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
You can use a suitable Writer:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");
It will create a file abc.txt if it doesn't exist. If it does, it will overwrite the file.
You can also open the file in append mode by using another constructor of FileWriter:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");
The documentation for above constructor says:
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:
File f = new File("myfile.txt");
if (f.createNewFile()) {
// If there wasn't a file there beforehand, there is one now.
} else {
// If there was, no harm, no foul
}
// And now you can use it.

Java FileWriter not writing to file

I'm creating an app which requires to write a file for every user (in JSON format).
The app successfully creates the file, But it's empty. In the code I added a finer output to see how the converted JSON String looks like, and I noticed that it's complete (it contains everything, so the conversion is ok). But the string isn't present in the file.
//create a new FileWriter C:/.../42.guser
FileWriter writer = null;
//for every User
for(int i=0; i<users.size(); i++) {
try {
File f = new File(Users.usersDir.getPath()+"/"+i+".guser");
//Create new file
f.createNewFile();
writer = new FileWriter(f);
//convert to json and write to file. Here we get the object with KEY = keys[i].
String stringedUsr = gson.toJson(users.get(keys[i]));
logger.finer("Converted user: \""+stringedUsr+"\""); //Output seems ok
//Write (NOT WORKING)
writer.write(stringedUsr);
logger.fine("Wrote updated user \""+keys[i]+"\" to file "+f.getCanonicalPath());
} catch (IOException e) {
FAILS++;
e.printStackTrace();
}
}
//End of for
What am I doing wrong?
Note: i gave to the app all the necessary Permissions. No AccessControlExceptions
First of all think about closing your writer.
When closing, it should flush() your data first (as mentioned in the doc here)
You can also flush() manually.

Delete the content of csv file in Java

Every day I update a csv file using a FileWriter. When we step into a new month I have to delete the data from the previous month. My below code only updates a data in a csv file so, please help in deleting the previous month's data.
At least I need to know how to delete the data in csv file using FileWriter, so that I can manage to code for deleting previous month data.
private static void eventsUpdate(HttpServletRequest request,
HttpServletResponse response) {
String date=request.getParameter("date"); //getting from jsp page
String event=request.getParameter("event"); //getting from jsp page
File file = new File( "D:///events/events.csv");
if ( !file.exists() )
file.createNewFile();
FileWriter fw = new FileWriter(file,true);
BufferedWriter writer = new BufferedWriter( fw );
writer.write(date);
writer.write(",");
writer.write(event);
System.out.println("writing into excel");
writer.newLine();
writer.close();
fw.close();
}
Actually when you use the true argument in your FileWriter instantiation, you create a file writer object in append mode.
FileWriter fw = new FileWriter(file,false);
If you don't use the true option, the file will be overwritten by the new content. Therefore, I would suggest to follow this roadmap:
Read the file content as a whole, in a String
Remove the content you want to remove from the specific String
Overwrite the file
content using your new content in the specific String
Hope I helped!
I suggest you that you may create unique name file like march2014, january2013 instead of deleting it. Every month you need to read your target file which is named by your month strategy.
For ex:
When you reach april2014, create a new file april2014 etc. and read it for that month.

File Delete and Rename in Java

I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.
import java.io.*;
class ModifyXML {
public void readMyFile(String inputLine) throws Exception
{
String record = "";
File outFile = new File("tempFile.tmp");
FileInputStream fis = new FileInputStream("InfectiousDisease.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
while ( (record=br.readLine()) != null )
{
if(record.endsWith("<add-info>"))
{
out.println(" "+"<add-info>");
out.println(" "+inputLine);
}
else
{
out.println(record);
}
}
out.flush();
out.close();
br.close();
//Also we need to delete the original file
//outFile.renameTo(InfectiousDisease.xml);//Not working
}
public static void main (String[] args) {
try
{
ModifyXML f = new ModifyXML();
f.readMyFile("This is infectious disease data");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thanks
First delete the original file and then rename the new file:
File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");
if(inputFile.delete()){
outFile.renameTo(inputFile);
}
A good method to rename files is.
File file = new File("path-here");
file.renameTo(new File("new path here"));
In your code there are several issues.
First your description mentions renameing the original file and adding some text to it. Your code doesn't do that, it opens two files, one for reading and one for writing (with the additional text). That is the right way to do things, as adding text in-place is not really feasible using the techniques you are using.
The second issue is that you are opening a temporary file. Temporary files remove themselves upon closing, so all the work you did adding your text disappears as soon as you close the file.
The third issue is that you are modifying XML files as plain text. This sometimes works as XML files are a subset of plain text files, but there is no indication that you attempted to ensure that the output file was an XML file. Perhaps you know more about your input files than is mentioned, but if you want this to work correctly for 100% of the input cases, you probably want to create a SAX writer that writes out all a SAX reader reads, with the additional information in the correct tag location.
You can use
outFile.renameTo(new File(newFileName));
You have to ensure these files are not open at the time.

Categories

Resources