File Writer How to Stop Over Writing text from file [duplicate] - java

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 8 years ago.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class test3 {
public static void main(String[] args) {
//write
try {
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt");
PrintWriter pw = new PrintWriter (fw);
pw.println("This is just some test data");
pw.close();
}
catch (IOException e){
System.out.println("Error!");
}
//read
try {
FileReader fr = new FileReader("C:\\Users\\Danny\\Desktop\\Credits.txt");
BufferedReader br = new BufferedReader (fr);
String str;
while ((str = br.readLine()) != null ) {
System.out.println(str + "\n");
}
br.close();
}
catch (IOException e){
System.out.println("File not found!");
}
}
}
This works but over writes the text file each time with the new input. How do I stop this over writing so that all information is stored in the file like an archive.

Pass true to your FileWriter like this -
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);
The second parameter to the FileWriter constructor will tell it to append to the file.
Docs --> http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,boolean)

Open the file in Append mode the next time you want to write to file.
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);

Use:
Files.newBufferedWriter(Paths.get("yourfile"), StandardCharsets.UTF_8,
StandardOpenOption.APPEND);

Related

I need to manipulate millions of data from a text file and after applying some of the queries i need another file using file input and output stream

i have a java code whose functioning is it readers a file using file input stream and after applying some conditions give another file using file output stream
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class Files {
public static void main(String[] args) {
try {
File file = new File("File1.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
File write = new File("File2.txt");
FileWriter fw = new FileWriter(write, true);
BufferedWriter out = new BufferedWriter(fw);
String line;
while ((line = br.readLine()) != null) {
String[] arr = line.split("#");
if (Integer.parseInt(arr[0]) >= 10000) {
out.write(arr[1]);
out.newLine();
}
}
System.out.println("SUCCESS");
br.close();
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
if I want to read millions of data from file and write millions of data in another file how can I edit my code in that case to make my code run fast
I want to make my code fast so that I can fetch or manipulate millions of data

Why has this file I/O operation in Java caused NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.
/**
* Remove certain lines from a text file.
*/
import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class LineCutter {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java LineCutter filename");
System.exit(1);
}
System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
FileReader fr = null;
FileWriter fw = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
fr = new FileReader(args[1]);
br = new BufferedReader(fr);
fw = new FileWriter(new File("output.txt"));
bw = new BufferedWriter(fw);
String line = br.readLine();
while(line != null) {
if (!line.equals(lineToRemove))
bw.write(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
br.close(); // NullPointerException
fw.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Operations finished.");
}
}
If fr = new FileReader(args[1]) throws an exception then br will be null when you attempt to call br.close() and the NullPointerException will hide the actual problem. Your problem is most likely the use of 1 as the index causing an ArrayIndexOutOfBoundsException. You expect only one element in the args array, so you should be using args[0]. Remember, arrays are zero-based.
Also, you should be using a try-with-resources statement. It handles closing everything for you automatically in a null-safe manner. For example:
try (BufferedReader br = new BufferedReader(new FileReader(args[0]));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))) {
// I/O code...
} catch (IOException ex) {
ex.printStackTrace();
}
Not sure what the following code is supposed to be doing:
System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
You don't do anything with result of lineToRemove.nextLine(). Though later you test if a String is equal to lineToRemove, which will always be false. Perhaps you mean:
String lineToRemove = new Scanner(System.in).nextLine();
Probably because fr = new FileReader(args[1]); is throwing an exception (probably because it can't find the file specified in args[1]), and so br continue to be null, and so you are invoking .close() in a null object.
I would also point out that here:
if (!line.equals(lineToRemove))
bw.write(line);
you are invoking equals between a String and a Scanner

Java: reading file and then writting data on a text file

How to read a file and then write the data into a .txt file in java? Below is my code. I am reading a file with extension .ivt. There are some tables in .ivt and reset is a text that describes what data is all about. I have to read the text stored in the file and then write it on a text file. I was able to get the data and write it on text file as well. But, when I open the text file and look at what is written, I see many lines of random symbols and spaces. Then, few lines are converted from English to French. I am struggling to find why this is happening. Does this problem occurs while reading data? or is there something wrong with the code?
package description;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
public class FileDescription
{
public static void main(String[] args)
{
// create variables
ArrayList<String> fileLines = new ArrayList<>();
String currLine;
// create file
File file = new File("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\Products.ivt");
FileInputStream fis = null;
BufferedReader br = null;
try
{
fis = new FileInputStream(file);
// construct buffered reader
br = new BufferedReader(new InputStreamReader(fis));
}
catch (FileNotFoundException e)
{
}
try
{
while((currLine = br.readLine()) != null)
{
// add line to the arrayList
fileLines.add(currLine);
}
}
catch (IOException e)
{
}
finally
{
// close buffered reader
try
{
br.close();
}
catch (IOException e)
{
}
}
// write ArrayList on file
PrintWriter pw = null;
try
{
pw = new PrintWriter("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt");
}
catch (IOException e)
{
}
for (int i = 0; i < fileLines.size(); i++)
{
pw.println(fileLines.get(i));
}
}
}
The code seems correct. Just remember to close output writer too. Without specify anything else, you are using plaftorm encoding. I think it's an encoding problem. You can try to read and write in UTF-8 encoding.
For the buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("filename.txt"), StandardCharsets.UTF_8));
And for the writer
pstream = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"), StandardCharsets.UTF_8), true);
To edit result, use an editor with UTF-8.
Reference 1
Reference 2

how to write on file after the text already present int that file (cursor movement to the end of the file)

This is my code for reading file and writing file ; i want to write string content to the end of the text file. My aim is to have command on cursor movement/controlling in a text file.
please help me out thanks
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Filing {
public static void main(String[] args) throws IOException
{
String content = "This is the content to write into file";
BufferedReader br =
new BufferedReader(new FileReader("C:/Users/Ashad/Desktop/text.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt");
BufferedWriter bw = new BufferedWriter(fw);
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
//** bw.write(content) ; **//
String everything = sb.toString();
System.out.append(everything);
}
finally
{ br.close();}
I couldnot write String content after the text already present on the file.
i want to write string content to the end of the text file
Then just use the overload of the FileWriter constructor that takes an append flag:
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true);
Personally though, I'd prefer to use FileOutputStream and an OutputStreamWriter - that way you can specify the encoding.
Create the FileWriter in append mode:
FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true);

Java Read / Write To File - BufferedReader BufferedWriter [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is a code snippet but basically what I want to do is read from a file named 'listings.txt' and write to a file named 'overview.txt'. I want to take the information out of 'listings.txt' and put them into 'overview.txt' as is (I will figure out the rest later).
The file 'overview.txt' is created and appears to loop through the file 'listings.txt' and write to 'overview.txt'. However, once I open the file 'overview.txt' it is empty. Could someone go through a quick glance at my code and spot something erroneous?
package yesOverview;
import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class yesOverview {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = "foo.bar";
System.out.print("Please enter the listings file (the full path to the file): ");
strInput = input.next();
//This makes sure that the inputed file is listings.txt as required for KET1 task 2
while (strInput.contains("listings.txt") == false) {
System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
strInput = input.next();
}
infos(strInput);
input.close();
}
public static void infos(String strInput) {
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter the overview.txt file (the full path to the file): ");
String strInput2 = "foo.bar";
strInput2 = input2.next();
//This also makes sure that the overview.txt file is provided.
while (strInput2.contains("overview.txt") == false) {
System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
strInput2 = input2.next();
}
//Creates the file f then places it in the specified directory.
File f = new File(strInput2);
try {
//Creates a printerwriter out that writes to the output file.
PrintWriter out = new PrintWriter(strInput2);
} catch (FileNotFoundException ex) {
Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
}
//String that holds the value of the next line.
String inputLine = "";
//Creates the Buffered file reader / writer.
try {
BufferedReader in = new BufferedReader(new FileReader(strInput));
FileWriter fstream = new FileWriter(strInput2);
BufferedWriter out = new BufferedWriter(fstream);
while (in.readLine() != null) {
out.write(in.read());
}
in.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Try this
Close the BufferedWriter stream (ie out.close() )
try and use nextLine() instead of next(), as next() only takes in a single word, but for a complete line use nextLine(), though this doesnt seem to be the problem here.
What i do when i have to read and write to files, i normally follow these steps
For Reading from a file
File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((br.readLine())!=null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
For Writing to a file:
Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while (isDone) {
if (!isDone) {
br.write(new Scanner(System.in).nextLine());
}
}
public static long copy (Reader input, Writer output) throws IOException {
char[] buffer = new char[8192];
long count = 0;
int n;
while ((n = input.read( buffer )) != -1) {
output.write( buffer, 0, n );
count += n;
}
return count;
}
Usage Example:
copy( reader, new FileWriter( file ) );
You're not closing out.
The finally block for the writeList method cleans up and then closes the BufferedWriter.
finally {
if (out != null) {
System.out.println("Closing BufferedWriter");
out.close();
} else {
System.out.println("BufferedWriter not open");
}
}

Categories

Resources