This is rewriting the whole file. How do I append contents to existing file "Data.txt"?
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args)
{
try
{
String content = "This is the content to write into file";
BufferedWriter bw = new BufferedWriter(new FileWriter("Data.txt", true));
bw.append(content);
System.out.println("Done");
bw.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Although, your code work for me. You can test another way. Wrapped your BufferedWriter with PrintWriter and run.
String content = "This is the content to write into file";
PrintWriter out =new PrintWriter(new BufferedWriter(new FileWriter("Data.txt", true)));
out.append(content);
out.close();
Related
This is code that deletes the content of the file then writes on it
I want to write in the file without deleting the content and write on the last line
import java.io.*;
import java.util.Scanner;
public class SetValues {
public void setNumberPhone(String numberPhone) throws UnsupportedEncodingException {
Scanner input = new Scanner(System.in);
PrintWriter pr = null;
try {
input = new Scanner("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt");
pr = new PrintWriter("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt", "UTF-8");
} catch (FileNotFoundException e) {
System.out.println("Not Open" + e.getMessage());
System.exit(0);
}
if (input.hasNext()) {
pr.println(numberPhone);
}
pr.close();
}
}
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;
OutputStream os = Files.newOutputStream(Paths.get("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt"), APPEND);
PrintWriter pr = new PrintWriter(os);
pr.println("TEXT");
This will create an output stream wherein any output text will be appended to the current contents of the file. You can use the OutputStream to create a PrintWriter. More information can be found at the Java documentation
hello everyone im trying to save data in the notepad but i dont know how to save many lines. with this code i just can save once the data.
package Vista;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class notepad_Data {
public void escribir(String nombreArchivo) {
File f;
f = new File("save_data");
try {
FileWriter w = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(w);
PrintWriter wr = new PrintWriter(bw);
wr.append(nombreArchivo+" ");
bw.close();
} catch (IOException e) {
};
}
public static void main(String[] args){
notepad_Data obj = new notepad_Data();
obj.escribir("writing in the notepad");
}
}
i tried with this code in the escribir method but doesnt work
for(int i=0; i<1000; ++i){
try {
FileWriter w = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(w);
PrintWriter wr = new PrintWriter(bw);
wr.append(nombreArchivo+" ");
bw.close();
} catch (IOException e) {
};
}
Every time you execute the program, you create a new sava_data file that replaces the previous file with the same name, so your new content is not added.
public class Notepad_Data {
public void escribir(String nombreArchivo) {
FileWriter fw = null;
try{
File f = new File("save_data");
fw = new FileWriter(f, true);
}catch(Exception e){
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(nombreArchivo);
pw.flush();
try{
fw.flush();
pw.close();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
Notepad_Data obj = new Notepad_Data();
obj.escribir("writing in the notepad11");
}
}
You should place your wr.append inside the loop using the arrayList.size as your condition, what you did here is you placed the whole block inside a for loop, which is not a good idea, one reason is you keep on creating an object of those 3 classes: FileWriter, BufferedWriter and PrintWriter, which is a potential java.lang.OutOfMemoryError: Java heap space error.
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:
Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
/**
* Created by FakeOwl96 on 3/28/2017.
*/
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.nextLine();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.next();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
The only change I made is
String fileName = keyboard.next(); from //keyboard.nextLine()
The above code worked for me . Hope this helps.
Add following line after initializing myFile:
myFile.createNewFile(); // if file already exists will do nothing
This is another example of file append line and create new file if file is not exists.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {
public static void main(String[] args) {
try {
File file = new File("myfile2.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();
System.out.println("Data successfully appended at the end of file");
} catch (IOException ioe) {
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
This is an example of file append line and create new file if file is not exists.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {
public static void main(String[] args) {
try {
String content = "This is my content which would be appended "
+ "at the end of the specified file";
//Specify the file name and path here
File file = new File("myfile.txt");
/* This logic is to create the file if the
* file is not already present
*/
if (!file.exists()) {
file.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(file, true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully appended at the end of file");
} catch (IOException ioe) {
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Yet, another example, this time with try-with-resources and using the Files class to create the BufferedWriter:
public void write(File file, String text) throws IOException {
Path path = file.toPath();
Charset charSet = StandardCharsets.UTF_8;
OpenOption[] options = new OpenOption[]{
StandardOpenOption.CREATE, // Create a new file if it does not exist
StandardOpenOption.WRITE, // Open for write access
StandardOpenOption.APPEND // Bytes will be written to the end of
// the file rather than the beginning
};
try (BufferedWriter bw = Files.newBufferedWriter(path, charSet, options)) {
bw.write(text);
}
}
The above example is available on GitHub with tests.
You can also use the Files.write method:
public void write(File file, List<String> lines) throws IOException {
Path path = file.toPath();
Charset charSet = StandardCharsets.UTF_8;
OpenOption[] options = new OpenOption[]{
StandardOpenOption.CREATE, // Create a new file if it does not exist
StandardOpenOption.WRITE, // Open for write access
StandardOpenOption.APPEND // Bytes will be written to the end of
// the file rather than the beginning
};
Files.write(path, lines, charSet, options);
}
i just need your help. I'm learning java(OOP) and now days we are working on filing. But i got stuck on how to append data in the file. I have written the code and and here's the part of it which is showing the error. Can someone please help me what's wrong with it and why it is not working?
package appending;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class open {
Formatter output;
public void openFile() throws FileNotFoundException {
output = new Formatter("E:/thisFile.txt");
}
public void addData() {
Scanner input = new Scanner(System.in);
data d = new data();
System.out.println("Enter the data");
d.setData(input.next(),input.nextInt());
output.format("%s","Name and CMS:\t"+d.getData());
FileWriter fileWritter = new FileWriter(File.getPath(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(d.getData());
bufferWritter.close();
}
public void close() {
output.close();
}
}
Can try,
public class FileAppend {
public static void main(String[] args) {
PrintWriter out = null;
try{
out = new PrintWriter(new BufferedWriter(new FileWriter("/home/rakesh/myfile.txt", true)));
out.println("appended text");
} catch(Exception e){
e.printStackTrace();
} finally{
out.close();
}
}
}
Creating a text file (note that this will overwrite the file if it already exists):
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file (will also overwrite the file):
byte dataToWrite[] = //...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(dataToWrite);
out.close();
Answer gotten from: How do I create a file and write to it in Java?
If you want to use FileWriter. Try following code:
//FileWriter fw = new FileWriter(new File("path/to/test.txt"), true);
FileWriter fw = new FileWriter("path/to/test.txt", true);
fw.write("This is a sentence");
fw.close();
EDIT You should follow the conventions and capitalize your classes.
Ok, so I am trying to save a multi-line string to a text file, without overwriting the previous text. println perfectly prints it, but saving to to a text file only seems to save the first line.
What I have so far (writes without overwriting, but only writes first line):
try {
FileWriter fileWriter = new FileWriter(FileManager.usernames, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(multilineString + "\n");
bufferedWriter.close();
}
catch(IOException e) {
e.printStackTrace();
}
The answer to this is probably simple, but I am new to Java.
you should try bufferedWriter.flush(); Here is code snippet which may help you
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteIntoFile {
public static void main(String[] args) {
String multilineString = "This is line 1\nthis is line 2\nthis is last line";
try {
FileWriter fileWriter = new FileWriter("multiline.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(multilineString + "\n");
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}