This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 9 years ago.
I am taking a number of inputs from the user like Name,age,e-mail etc.. , and I concatenated all these fields with a ":" delimiter
`String line = Anjan+":"+21+":"+abc#abcd.com;`
My question is:
How do I write the String line into a file?
I repeat the process of taking inputs from users. Can somebody explain me, how can I write the line to a file each time, after I am done with reading and concatenating the inputs?
If you are using java 7 it will be quite easy,
public void writerToPath(String content, Path path) throws IOException {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path,StandardOpenOption.CREATE, StandardOpenOption.APPEND)))){
writer.newLine();
writer.write(content);
}
}
Since Writer implements the AutoClosable interface will the writer and underlying streams be closed when finished or if an exception occur.
public static void write(final String content, final String path)
throws IOException {
final FileOutputStream fos = new FileOutputStream(path);
fos.write(content.getBytes());
fos.close();
}
Try the following code. You can create method and pass values as parameter. It'll append the new line every time. It won't remove existing lines(data)
File logFile = new File( System.getProperty("user.home") + File.separator + "test.txt");
String data = "value";
if(!logFile.exists()){
logFile.createNewFile();
}
FileWriter fstream = new FileWriter(logFile.getAbsolutePath(),true);
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(data);
fbw.newLine();
fbw.close();
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java append to file
How to append data to a file?
I want to write a file in java without cleaning(deleting) older data
This is my try, but the current data will be cleaned on writing new data.
import java.io.*;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "New content to write to file";
File file = new File("/mypath/filename.txt");
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use constructor FileWriter(String filename, boolean append) that can instruct the file to be opened in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
//^^^^ means append
Try
FileWriter fw = new FileWriter(file, true);
Notes: second param means append; no need for file.getAbsoluteFile(), just File is OK
open the file in append mode .
like
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
FileWriter takes a boolean argument which specifies whether to overwrite or not.
Try this :
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
also visit :
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29
This question already has answers here:
How to Write text file Java
(8 answers)
Closed 6 years ago.
I have Come across so many programmes of how to read a text file using Scanner in Java. Following is some dummy code of Reading a text file in Java using Scanner:
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
But, please anyone help me in "Writing" some text (i.e. String or Integer type text) inside a .txt file using Scanner in java. I don't know how to write that code.
Scanner can't be used for writing purposes, only reading. I like to use a BufferedWriter to write to text files.
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();
Scanner is for reading purposes. You can use Writer class to write data to a file.
For Example:
Writer wr = new FileWriter("file name.txt");
wr.write(String.valueOf(2)) // write int
wr.write("Name"); // write string
wr.flush();
wr.close();
Hope this helps
This question already has answers here:
Write to text file without overwriting in Java
(9 answers)
Closed 8 years ago.
Hi there I'm trying to write strings to a textfile but there is a little problem. I completed my code with the help of the other questions at this site but when i try to add strings to a text file it erases everything in that text file and writes the input. But I want it to go to the nextline and write it. I couldn't solve it. I would appreciate any help. Thank you..
public static void addCar() throws IOException{
String string = transferBrand;
String string2 = ":"+transferModel;
System.out.println(string+string2);
File file = new File("HatchBack.txt");
try {
StringReader stringReader = new StringReader(string+string2);
BufferedReader bufferedReader = new BufferedReader(stringReader);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String line = bufferedReader.readLine(); line != null; line =bufferedReader.readLine()) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
(untested) Did you try this as mentioned in JavaDoc?
FileWriter fileWriter = new FileWriter(file, true);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java append to file
How to append data to a file?
I want to write a file in java without cleaning(deleting) older data
This is my try, but the current data will be cleaned on writing new data.
import java.io.*;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "New content to write to file";
File file = new File("/mypath/filename.txt");
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use constructor FileWriter(String filename, boolean append) that can instruct the file to be opened in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
//^^^^ means append
Try
FileWriter fw = new FileWriter(file, true);
Notes: second param means append; no need for file.getAbsoluteFile(), just File is OK
open the file in append mode .
like
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
FileWriter takes a boolean argument which specifies whether to overwrite or not.
Try this :
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
also visit :
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29
i was wondering if there was a way to add to text files already created. because when i do this on an already created file:
public Formatter f = new Formatter("filename.txt");
it re-writes the current filename.txt with a blank one.
thanks, Quinn
Yes, use the constructor with an OutputStream argument instead of a File argument. That way you can open an OutputStream in append mode and do your formatting on that. Link
Try using the constructor for Formatter which takes an Appendable as an argument.
There are several classes which implement the Appendable interface. The most convenient, in your case, should be FileWriter.
This FileWrite constructor will let you open a file (whose name is specified as a String), in append mode.
Use FileOutputStream with append boolean value as true eg new FileOutputStream("C:/concat.txt", true));
Example
public class FileCOncatenation {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/concat.txt", true));
File file2 = new File("C:/Text/file2.rxt");
System.out.println("Processing " + file2.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(file2
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
// }
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}
}