how to save data into notepad from java - java

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.

Related

Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?

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);
}

how to append the data in java file?

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.

Creating, writing and editing same text file in java

Let's say I have the following code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( br.readLine() != null ){
verify = br.readLine();
if(verify != null){
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".
I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.
Change your code to that:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null ){ //***editted
//**deleted**verify = br.readLine();**
if(verify != null){ //***edited
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
The Problem is that you are calling br.readLine() twice which is provoking the application to read line1 and then line2 and in your case you have just one line which means that your program read it in the conditional form and when it comes to declaring it to the variable verify, it is stopping because you don't have anymore data to read your file.
I would do it this way:
import java.io.*;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null )
{
if(verify != null)
{
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
use this code, I used it to remove logs and System.out statements in java file.
just change the matching and replacing string.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
Scanner scan = null;
public void doIt() {
scan = new Scanner(System.in);
while (true) {
try {
System.out
.println("enter qualified file name ex.D:\\shiv\\shiv android all\\Main work space\\Welcomescreen1.java");
String path = scan.nextLine();
File f1 = new File(path);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null) {
if (line.contains("System.out")) {
line = line.replace("System.out", "//");
} else if (line.contains("Log.")) {
line = line.replace("Log", "//");
}
lines.add(i, line);
i++;
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for (int j = 0; j < lines.size(); j++) {
System.out.println(j + "." + lines.get(j));
out.append(lines.get(j));
out.newLine();
}
out.flush();
out.close();
System.out
.println("====================work done===================");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
import java.io.*;
public class TextFile
{
public static void main(String[] args)
{
try
{
String verify, putData;
File file = new File("G:\\Dairy.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("I am Shah Khalid");
bw.flush();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null )
{
if(verify != null)
{
putData = verify.replaceAll("here", "there");
//bw.write(putData);
}
}
br.close();
bw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Shah");
}
}
There is no need to type bw.write(putData);, because it will just print the statement twice.
Whatever you want in a file, just give the correct path of the file and use the above code accordingly.
File file = new File("/tmp/my.txt");
FileWriter fw;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String line;
String data="";
String lessonPath="my new line";
try {
if(!file.exists()){
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(lessonPath);
bw.flush();
bw.close();
}else{
br = new BufferedReader(new FileReader(file));
while((line =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+line;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
bw.flush();
bw.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}

Unable to append data to file using BufferedWriter

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();

Java: PrintWriter

I am trying to use PrintWriter.java but I am getting a rather strange problem and I am not able to figure out what am I am missing here.
MyPrintWriter.java
public class MyPrintWriter {
public static void main(String[] args) {
File myFile = new File("myFileDirectory/myFileName.txt");
try {
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello World!");
pw.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + myFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyFileWriter.java
public class MyFileWriter {
public static void main(String[] args) {
File myFile = new File("myFileDirectory/myFileName.txt");
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
String input;
input = br.readLine();
while(input != null) {
pw.println(input);
input = br.readLine();
}
br.close();
pw.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + myFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyPrintWriter.java is happily writing to the myFileName.txt file but MyFileWrite.java can't.
Could someone help me understand what am I missing here?
You probably need to flush your print writer.
The PrintWriter constructor with a FileWriter parameter creates a PrintWriter with autoFlush set to off
Calling pw.flush() before pw.close(); should do the trick

Categories