i am new developer in android.i would like to write some content to a file i have used a method to write into a file as follows
public void writeFile(String path,String text){
try{
Writer output = null;
File file = new File(path);
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");
}
catch (Exception e) {
e.printStackTrace();
}
here i am passing path of a file and text to write.if i use in this way i can write the data but the previous data is losing.
how can i append or insert the latest text into a file without losing previous text?
Thanks in advance
Try this. Change this line ...
output = new BufferedWriter(new FileWriter(file));
to
output = new BufferedWriter(new FileWriter(file, true));
The true indicates that you want to append not overwrite
Have a look here and try:
new FileWriter(file, true);
the boolean indicates whether or not to append to an existing file.
Related
I'm working with opencsv librarie in Eclipse and when I write something in a .csv I don't know in which folder is created. I should say that I need that the .csv file is not deleted when i turn off the app, so I can store in the assets folder, right?
My code is this:
try {
String csv = "data.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
//Create record
String [] record = "hello,world".split(",");
//Write the record to file
writer.writeNext(record);
//close the writer
writer.close();
} catch (IOException e) {}
May be you can find it file at "/data/data/your_project_package_structure/files/data.csv"
Still don't find the You can do like this. file.getAbsolutePath() gives you full path there you can identify where your file getting stored:
try
{
File file = new File("data.csv");
// creates the file of name data.csv
file.createNewFile();
//you can print absolute path of file
System.out.println(file.getAbsolutePath());
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
//pass to csv writer
CSVWriter writer = new CSVWriter(new FileWriter(csv));
//Create record
String [] record = "hello,world".split(",");
//Write the record to file
writer.writeNext(record);
//close the writer
writer.close();
} catch (IOException e) {
}
I have an application that creates a .txt file. I want to overwrite it. This is my function:
try{
String test = "Test string !";
File file = new File("src\\homeautomation\\data\\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :
default mode, which overwrites the whole file
append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
You don't need to do anything, the default behavior is to overwrite.
No clue why I was downvoted, seriously... this code will always overwrite the file
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
Just call file.delete() in your else block. That should delete the file, if that's what you want.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
The Below one line code will help us to make the file empty.
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
try{
File file = new File("src\\homeautomation\\data\\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
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();
}
The following code does not produce a file (I can't see the file anywhere).
What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases.
The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
In java 7 can now do
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
and w.close will be done automatically
It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.
File newFile = new File("directory", "fileName.txt");
You can do this to make a file:
newFile.createNewFile();
You can do this to make a folder:
newFile.mkdir();
Using java 8 LocalDateTime and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You can try a Java Library. FileUtils, It has many functions that write to Files.
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
The easiest way for me is just like:
try {
FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
writer.write("Wow, this is so easy!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Useful tips & tricks:
Give it a certain path:
new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
New line
writer.write("\r\n");
Append lines into existing txt
new FileWriter("log.txt");
Hope it works!
I have a result being entered into a file. This result is being done on a loop. So, every time a new result comes, it has to be appended into a file, but it is being overwritten. What should I use in order to append my results into a single file?
Try
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
}
catch (IOException e) {
// handle exception
}
finally{
if(out != null){
try{
out.close();
}
catch(IOException e){
// handle exception
}
}
}
According to the API,
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.
here is the basic snippet
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java 1");
out.write("Hello Java 2");
See Also
FileWritter - Javadoc
You should either keep the file open (sometimes it better, but usually not...) or open the output stream in append mode:
OutputStream os = new FileOutputStream(file, true);