How to save a string to a .txt file in java [duplicate] - java

This question already has answers here:
How do I save a String to a text file using Java?
(24 answers)
Closed 8 years ago.
Ive finished an application and have tested all the functions and they are working. However one part of inputted data is supposed to be saved to a .txt file. Ive placed this inside a string but Im a bit out of my depth in this area and have no idea how to save this to a drive on my PC. Any help is appreciated. The code is on this link: http://sharetext.org/fSy2

Try This:
public static void main(String args[])throws IOException {
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
}
Read more abut here

Related

How to append to existing file [duplicate]

This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 4 years ago.
I am trying to redirect the console input to a file. Problem is that every time i create a file it overwrites it or creates new files if I select the name of file to include unix timestamp. I saw similar questions here but I am not sure which approach or class to use.
PrintStream out;
PrintStream oldout = new PrintStream(System.out);
try {
out = new PrintStream(
new FileOutputStream(
workFolder + File.separator + "output" + Instant.now().getEpochSecond() + ".txt"));
System.setOut(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.setOut(oldout);
So if there isn't a file to create it, but if there is already a file to just append new data, but not overwrite or create new files.
As per Java docs
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Parameters: name - the system-dependent file name
append - if true,
then bytes will be written to the end of the file rather than the
beginning
There is a constructor which allows passing the boolean value which decides whether to append the data in file or not.
You can use it.

How to make BufferedWriter not overwrite a text file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I am currently making an application where the user can add multiple accounts. The login information is being stored in a text file. I need a way for the user to add a new account without BufferedWriter overwriting the other accounts' information. Any suggestions?
package mainFiles.fileManagers;
import java.io.*;
public class NewTXT {
public static void nFile( String a , String b ) throws IOException {
File f = new File("mainFiles\\storage\\accountinfo.txt");
FileWriter writer = new FileWriter("mainFiles\\storage\\accountinfo.txt");
BufferedWriter bWriter = new BufferedWriter(writer);
f.createNewFile();
f.canWrite();
bWriter.newLine();
bWriter.write(a + "?" + b );
bWriter.newLine();
bWriter.close();
}
}
There is nothing wrong with the BufferedWriter. You have to construct the FileWriter in append mode:
FileWriter writer = new FileWriter("mainFiles\\storage\\accountinfo.txt", true);
Check the FileWriter documentation:
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

Writing to a txt file without clearing the previous content [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 6 years ago.
I want to know how do I write a line to a file without clearing or flushing it. What classes and packages do I need?
I've tried with FileOutputStream and PrintStream (using println) and with BufferedWriter and OutputStreamWriter (using write) but they erase the previous content from the file.
try
{
File txt = new File("marcos.txt");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
writer.write(registro);
writer.newLine();
writer.close();
}
catch(Exception e)
{
System.out.println("Error en la escritura al archivo.");
}
You can use the method writeStringToFile under the class FileUtils from org.apache.commons.io
public static void writeStringToFile(File file,
String data,
Charset encoding,
boolean append)
throws IOException
Writes a String to a file creating the file if it does not exist.
Parameters:
file - the file to write
data - the content to write to the file
encoding - the encoding to use, null means platform default
append - if true, then the String will be added to the end of the file rather than overwriting
Throws:
IOException - in case of an I/O error

Java - how to replace file contents? [duplicate]

This question already has answers here:
Is this the best way to rewrite the content of a file in Java?
(8 answers)
Closed 6 years ago.
I have a file that contains only a very small amount of information that needs to be updated periodically. In other words, I want to truncate the file before writing to it. The easiest solution I found was to delete and create it again as shown here:
File myFile = new File("path/to/myFile.txt");
myFile.delete();
myFile.createNewFile();
// write new contents
This 'works' fine, but is there a better way?
There is no need to delete the file and recreate one. If you are writing to the file, for instance using PrintWriter, it will overwrite your current file content.
Example:
public static void main(String[] args) throws IOException
{
PrintWriter prw= new PrintWriter (“MyFile.txt”);
prw.println("These text will replace all your file content");
prw.close();
}
It will only append to the end of the file if you use the overloaded version of the PrintWriter constructor:
PrintWriter prw= new PrintWriter (new FileOutputStream(new File("MyFile.txt"), true));
//true: set append mode to true
In the below example, the "false" causes the file to be overwritten, true would cause the opposite.
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();

How to add text to a text file in java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to append text to an existing file in Java
I want to add data to a text file. So it's one after another...so something like:
1
2
3
<add more here>
But I don't want the text from the file to be deleted at all. This is the code i'm using atm, but it replaces what ever is in the file. Could someone please tell me how to do what I asked. Thanks.
FileWriter fstream = new FileWriter("thefile.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("blabla");
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
use this
FileWriter fstream = new FileWriter("thefile.txt",true);
the explanation
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Categories