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.
Related
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);
}
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();
}
}
}
I have created a thread that should allow the user to input a string of characters into the command line and this should save, on a new line, to a file, called user_input.txt.
I managed to make it work while on the main thread, but I need to make it happen within a Thread.
Here is my code for the Thread object:
//Importing
//Input
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
//File writing
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileInputThread implements Runnable
{
public void run() {
System.out.println("FileInputThread running");
//Creating Instances of InputStreamReader and BufferedReader
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyboardInput = new BufferedReader(input);
//Finding/Creating File
File file = new File("/Users/jakecarr/Documents/University/Year 2/Semester 1" +
"/ECM2414 Software Development/Workshop 3/user_input.txt");
try {
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//Creating instances of FileWriter and BufferedWriter
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//Creating Date object
Date date;
//Output
System.out.println("Type what you want to write to file");
System.out.println("Please type 'ESC' to exit");
while (true) {
System.out.println("Inside While loop");
String string = keyboardInput.readLine();
//Checks if user types in ESC to stop program
if (string.equals("ESC")) {
System.out.println("You are finished");
break;
}
//Writing the input to the file
bw.write(string);
bw.newLine();
//Flushes strings on buffered reader to the hard drive
bw.flush();
}
System.out.println("Writing to file complete");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Right now, it seems to do all the println methods, I just doesn't allow you to type anything in at the command line when it comes to the keyboardInput.readLine(); and that is where it seems to get stuck!
I would be grateful for any help!
Thank you.
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();