I am working on a log file that is currently over-writing itself every single time. Now The thing is all i want it to do is to just write on the first line and append the list below to show the history from newest to oldest. Problem is I am not sure how to go about it I am looking at the code but don't know what I am doing wrong. Here is the code not sure if I am missing something or not.
String historylog = new Date().toString();
BufferedWriter bw = null;
String filepath = "C:\netbeans\Source code\test3";
String filename = "PatchHistory.log";
try
{
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs();
bw = new BufferedWriter( new FileWriter( filepath + File.separator
+ filename, true));
bw.write( historylog + "\r\n");
bw.newLine();
bw.flush();
bw.close();
return true;
}
catch (IOException){
return false;
}
Any Help would be appreciated not sure what I am doing wrong with this.
If I have understood you, you want to add log entries at the beginning of a log file.
AFAIK, (if you know any exceptions please tell me) all filesystems add data to the end of file. And Direct Access would overwrite the beginning of the file.
Your best option would be writting the log to a different file and, after writting what you want, write after that the contents of the original log file. Once done, close both files and overwrite the old file with the new one.
In your code
You are wrong here, you didn't used if statement properly.
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs(); // file path not exist, then it will execute
bw = new BufferedWriter( new FileWriter( filepath + File.separator + filename, true)); // this append file will always execute
Solution
if (!(f.exists())) {
//create new file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename, false));
}
else{
//append in existing file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename,true));
}
Related
I'm currently using FileWriter to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?
fout = new FileWriter(
"Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();
Pass true as a second argument to FileWriter to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference
From the Javadoc, you can use the constructor to specify whether you want to append or not.
public FileWriter(File file,
boolean append)
throws IOException
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.
You can open the FileWriter in append mode by passing true as the second parameter:
fout = new FileWriter("Distribution_" + ... + ".txt", true);
You may pass true as second parameter to the constructor of FileWriter to instruct the writer to append the data instead of rewriting the file.
For example,
fout = new FileWriter(
"Distribution_" + Double.toString(lowerBound) + "" + Double.toString(_highBound) + ".txt",true);
Hope this would solve your problem.
I am creating a dat file in C: drive folder named abc as shown below , Now my file is generated everyday
now suppose if my file is generated today, then tommrow it will be also generated as usual
but when tommrow it is generated I have to make sure that earlier day file is deleted as the space in that folder is limited and this check is every time need to be done previos day file to be get deleted from that folder , please advise how to achieve this..
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(
file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fileOutput));
why not use file.delete() ?
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (file.exists()) {
file.delete(); //you might want to check if delete was successfull
}
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutput));
If your file name same in time to time no need to delete that. By running your code tomorrow, will over write file created today.
Consider following case
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Test\test.txt"));
bw.write("abbbb");
bw.close(); // now this will create a test.txt in side Test folder
now run this by change writing String
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt"));
bw.write("hihi");
bw.close(); // now you can see file only containing hihi
You can change your code this way:
if (file.exists()) {
file.delete();
}
file.createNewFile();
And if it does not work, it's a matter of permission.
If you are using Java 7 then there is standard way to get file creation time, So that you can check if file is created in previous day and should be delete.
Path path = Paths.get("/filepath/");
BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("creationTime:"+ fileAttributes.creationTime());
Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
I'm currently trying to save a newly created text file to a directory that the user specifies. However, I don't see how it is possible with this code setup. Where does one specify where file is to be saved?
if(arg.equals(Editor.fileLabels[1])){
if(Editor.VERBOSE)
System.err.println(Editor.fileLabels[1] +
" has been selected");
filedialog = new FileDialog(editor, "Save File Dialog", FileDialog.SAVE);
filedialog.setVisible(true);
if(Editor.VERBOSE){
System.err.println("Exited filedialog.setVisible(true);");
System.err.println("Save file = " + filedialog.getFile());
System.err.println("Save directory = " + filedialog.getDirectory());
}
File file = new File("" + filedialog.getName());
SimpleFileWriter writer = SimpleFileWriter.openFileForWriting(filedialog.getFile() + ".txt");
if (writer == null){
System.out.println("Failed.");
}
writer.print("" + this.editor.getTextArea().getText());
writer.close();
}
FileChooser and FileWriter make things fairly easy, here is the java tutorial:
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
http://www.abbeyworkshop.com/howto/java/writeText/index.html
You call it like this:
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(aComponent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File toSave = fc.getSelectedFile();
FileWriter outWriter = new FileWriter(toSave);
PrintWriter outPrinter = new PrintWriter(outWriter);
outPrinter.println("" + this.editor.getTextArea().getText());
}
else
{
//user pressed cancel
}
Remember that it is the PrintWriter class that does the actual printing.
EDIT:
If you want the user to select directories only, call
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
before displaying it. Note that in this case you will have to specify a new File object WITHIN that directory in order to be able to write text to it (attempting to write the text to a directory will result in an IOException).
writer.print("" + this.editor.getTextArea().getText());
Don't use methods like that. All text components support a write(...) method. All you have to do is get the File name that you want to write the file to.
Something like:
JtextArea textArea = new JTextArea(....);
....
FileWriter writer = new FileWriter( "TextAreaLoad.txt" ); // get the file name from the JFileChooser.
BufferedWriter bw = new BufferedWriter( writer );
textArea.write( bw );
bw.close();
If you don't know how to use file choosers then read the section from the Swing tutorial on How to Use File Choosers.
I'm currently using FileWriter to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?
fout = new FileWriter(
"Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();
Pass true as a second argument to FileWriter to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference
From the Javadoc, you can use the constructor to specify whether you want to append or not.
public FileWriter(File file,
boolean append)
throws IOException
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.
You can open the FileWriter in append mode by passing true as the second parameter:
fout = new FileWriter("Distribution_" + ... + ".txt", true);
You may pass true as second parameter to the constructor of FileWriter to instruct the writer to append the data instead of rewriting the file.
For example,
fout = new FileWriter(
"Distribution_" + Double.toString(lowerBound) + "" + Double.toString(_highBound) + ".txt",true);
Hope this would solve your problem.