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.
Related
I am trying to transfer the data from old textfile to new textfile. Although the code below is able to transfer successfully, it does not delete the old textfile. May I know why is this so?
private void dataTransfer(String oldFilePath, String newFilePath) {
byte[] buffer = new byte[10000];
try {
FileInputStream fileInput = new FileInputStream(oldFilePath);
BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
FileOutputStream fileOutput = new FileOutputStream(newFilePath);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
while(true) {
int length = fileInput.read(buffer);
if(length == -1) {
break;
} else {
bufferedOutput.write(buffer);
bufferedOutput.flush();
}
}
fileInput.close();
bufferedInput.close();
fileOutput.close();
bufferedOutput.close();
File oldFile = new File(oldFilePath);
oldFile.delete();
} catch (IOException e) {
e.printStackTrace();
System.out.println(ERROR_TRANSFER_DATA);
}
}
Update the JRE and JDK, make sure you have the rights on the file. Try with a file created by you.
Also, add a catch block for SecurityException
For deleting a file it should work fine but for deleting a directory you have to make sure that Directory is Empty.
You can use the following code block. It works, though don't know. Even without setWritable, it works,
oldFile.setWritable(true);
if(!oldFile.delete()){
System.out.println("de;eted");
}
According to Oracle's docs, the delete method does not guarantee that it will delete the file.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete()
Deleting a file will fail if:
file does not exist
there is a lock on that file it might be opened by another process
file does not exist on the disk
you don't have enough permissions to delete that file (in this case a SecurityException is thrown)
I agree with #panagdu that you might not have sufficient rights to delete the file.
Just as a fluke try closing bufferedStream before fileInputStream
like
bufferedInput.close();
fileInput.close();
bufferedOutput.close();
fileOutput.close();
But I don't think this will help.
Test your code for files with sufficient permission. For example Java does not allow the delete() for system files.
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.
I'm using the following code for append new position data obtained by GPS, each time position change.
if (isExternalStorageWritable()) {
if (myFile.exists()) {
try {
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(location.getLatitude()+", "+location.getLongitude()+", "+nodeCounter+"\n");
myOutWriter.close();
fOut.close();
nodeCounter++;
} catch (Exception e) {
}
} else {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}else
{
Log.i("logGPSData","Error");
}
The problem is that the append does not work, since each time a new row is inserted, the previous row is overwritten, so my file contains always one line, even if I collect many gps data.
The second argument means if text should be appended to the existing file, change the following lines in your code:
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
to:
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut,true);
From the Docs:
public FileOutputStream(String name,boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called with name as its argument.
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
Parameters:
1) name - the system-dependent file name
2) append - if true, then bytes will be written to the end of the file rather than the beginning
Throws:
1)FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
2)SecurityException - if a security manager exists and its checkWrite method denies write access to the file.
Since:
JDK1.1
i need some help with creating file
Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:
getting a file object
creating a temporary file with similar name (how do i make sure the temp file will be created in same place as the given original one?)
write to this file
replace the original file on the disk with the temporary one (should be in original filename).
I look for a simple code who does that preferring with RandomAccessFile
I just don't how to solve these few steps right..
edited:
Okay so ive attachted this part of code
my problem is that i can't understand what should be the right steps..
the file isn't being created and i don't know how to do that "switch"
File tempFile = null;
String[] fileArray = null;
RandomAccessFile rafTemp = null;
try {
fileArray = FileTools.splitFileNameAndExtension(this.file);
tempFile = File.createTempFile(fileArray[0], "." + fileArray[1],
this.file); // also tried in the 3rd parameter this.file.getParentFile() still not working.
rafTemp = new RandomAccessFile(tempFile, "rw");
rafTemp.writeBytes("temp file content");
tempFile.renameTo(this.file);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
rafTemp.close();
}
try {
// Create temp file.
File temp = File.createTempFile("TempFileName", ".tmp", new File("/"));
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("Some temp file content");
out.close();
// Original file
File orig = new File("/orig.txt");
// Copy the contents from temp to original file
FileChannel src = new FileInputStream(temp).getChannel();
FileChannel dest = new FileOutputStream(orig).getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) { // Handle exceptions here}
you can direct overwrite file. or do following
create file in same directory with diff name
delete old file
rename new file
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.