Java how to write to a file and append to it [duplicate] - java

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 3 years ago.
I can't get this program to write 4 lines of text to the same file javafile.txt. The first two sentences get overwritten by the next two sentences. I'm using BufferedWriter to accomplish this. I have tried so many different things but I keep overwriting the first sentences the javafile.txt ......................................................................................................................................................................................................................................................................................................................
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
public class lab11_2 {
public static void main(String[] args) {
System.out.println("Practice writing to files \n");
File Myfile = new File("C:\\Users\\test\\Desktop\\lab11\\javafile.txt");
try {
if (Myfile.createNewFile()) {
System.out.println("File created: " + Myfile.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} //end create new file
try {
System.out.println("Write to to file");
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\test\\Desktop\\lab11\\javafile.txt"));
out.write("This is the first line of text in " + Myfile.getName() + "\n");
out.close();
out = new BufferedWriter(new FileWriter("C:\\Users\\test\\Desktop\\lab11\\javafile.txt",true));
out.write("This is the second line of text in " + Myfile.getName() + "\n");
out.close();
System.out.println("Succesfully wrote to the the file");
System.out.println();
}
catch (IOException e) {
System.out.println("exception occoured"+ e);
}
if (Myfile.exists()) {
System.out.println("Get file information:");
System.out.println("File name: " + Myfile.getName());
System.out.println("Absolute path: " + Myfile.getAbsolutePath());
System.out.println("Writeable: " + Myfile.canWrite());
System.out.println("Readable " + Myfile.canRead());
System.out.println("File size in bytes " + Myfile.length());
} else {
System.out.println("The file does not exist.");
}
System.out.println();
System.out.println("First read file");
try {
Scanner myReader = new Scanner(Myfile);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} // end try
System.out.println();
try {
System.out.println("Write to to file");
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\test\\Desktop\\lab11\\javafile.txt"));
out.write("This is the Third line of text in " + Myfile.getName() + "\n");
out.close();
out = new BufferedWriter(new FileWriter("C:\\Users\\test\\Desktop\\lab11\\javafile.txt",true));
out.write("This is the fourth line of text in " + Myfile.getName() + "\n");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured"+ e);
}
System.out.println("Done");
System.out.println();
}// end of main
}

See the FileWriter api.
You open a new FileWriter four times. Two of those times, you pass true as a constructor parameter, so the writer is in append mode. That means it adds to the file instead of overwriting it. The others, you don't use append mode, so your file is overwritten.
If you want to append to a file, change the third file writer to also use append mode. Otherwise at that point you overwrite the file containing the first two sentences.
Or better yet, don't open and close the file four times. Open it once and write everything you want to write, then close it at the end.

Related

How to Append Text in logical manner, etc

I'm experimenting on how to create a sign-up page using file handling, which will result into a text file: "database.txt". The first time you fill out the requirements. The results are fine but when you register again for the second time, it just append it and not setting it the way I like it and I like it to be it like this way.
I have searched for similar problems like this in various websites, links, but I can't seem to understand it.
Scanner input = new Scanner(System.in);
String filepath = "C:\\Users\\Sparda\\Desktop\\Database.txt";
try {
FileOutputStream fos = new FileOutputStream(filepath, true);
System.out.println("Enter Username");
String user = input.nextLine();
System.out.println("Enter Password");
String pass = input.nextLine();
String data = user + (",") + pass;
fos.write(data.getBytes());
System.out.println("Registered Successfully!");
}
catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException: " + ex.toString());
}
catch (IOException ioe) {
System.out.println("IOException: " + ioe.toString());
}
catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
}
}
The actual output is:
Patrick Archie, BuyainAshley,Flames
While my expected output should be:
Patrick Archie, Buyain
Ashley, Flames
You can write instead String data = user + (",") + pass + ("\n");

Java too many open files exception

I have a problem on my code; basically I have an array containing some key:
String[] ComputerScience = { "A", "B", "C", "D" };
And so on, containing 40 entries.
My code reads 900 pdf from 40 folder corresponding to each element of ComputerScience, manipulates the extracted text and stores the output in a file named A.txt , B.txt, ecc ...
Each folder "A", "B", ecc contains 900 pdf.
After a lot of documents, an exception "Too many open files" is thrown.
I'm supposing that I am correctly closing files handler.
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader = new FileReader(dizionario);
} catch (FileNotFoundException e) { }
try {
BufferedReader bufferedReader = new BufferedReader(fileReader);
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (! line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else { System.err.println("Dictionary file not found."); }
bufferedReader.close();
fileReader.close();
fileWriter.close();
} catch (IOException e) { return false;}
catch (NullPointerException ex ) { return false;}
finally {
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
But the error still comes. ( it is thrown at:)
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
Thank you.
EDIT: SOLVED
I found the solution, there was, in the main function in which writeOccurencesFile is called, another function that create a RandomAccessFile and doesn't close it.
The debugger sais that Exception has thrown in writeOccurencesFile but using Java Leak Detector i found out that the pdf were already opened and not close after parsing to pure text.
Thank you!
Try using this utility specifically designed for the purpose.
This Java agent is a utility that keeps track of where/when/who opened files in your JVM. You can have the agent trace these operations to find out about the access pattern or handle leaks, and dump the list of currently open files and where/when/who opened them.
When the exception occurs, this agent will dump the list, allowing you to find out where a large number of file descriptors are in use.
i have tried using try-with resources; but the problem remains.
Also running in system macos built-in console print out a FileNotFound exception at the line of FileWriter fileWriter = ...
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
try (FileWriter fileWriter = new FileWriter( "files/" + categoria + ".txt" , true)) {
try (FileReader fileReader = new FileReader(dizionario)) {
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (!line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else {
System.err.println("Dictionary file not found.");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
This is the code that i am using now, although the bad managing of Exception, why the files seem to be not closed?
Now i am making a test with File Leak Detector
Maybe your code raises another exception that you are not handling. Try add catch (Exception e) before finally block
You also can move BufferedReader declaration out the try and close it in finally

FileWriter not appending to existing file

I am writing a method that takes in a List of Twitter Status objects as a parameter, opens a log file containing String represenatations of Tweets, checks if any of the String representations of the Status objects are already written to the file - if so, it removes them from the list, if not it appends the Status to the file.
Everything is working up until I attempt to write to the file. Nothing is being written at all. I am led to believe that it is due to the method having the file open in two different places: new File("tweets.txt") and new FileWriter("tweets.txt, true).
Here is my method:
private List<Status> removeDuplicates(List<Status> mentions) {
File mentionsFile = new File("tweets.txt");
try {
mentionsFile.createNewFile();
} catch (IOException e1) {
// Print error + stacktrace
}
List<String> fileLines = new ArrayList<>();
try {
Scanner scanner = new Scanner(mentionsFile);
while (scanner.hasNextLine()) {
fileLines.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
// Print error + stacktrace
}
List<Status> duplicates = new ArrayList<>();
for (Status mention : mentions) {
String mentionString = "#" + mention.getUser().getScreenName() + " \"" + mention.getText() + "\" (" + mention.getCreatedAt() + "\")";
if (fileLines.contains(mentionString)) {
duplicates.add(mention);
} else {
try {
Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true));
writer.write(mentionString);
} catch (IOException e) {
// Print error + stacktrace
}
}
}
mentions.removeAll(duplicates);
return mentions;
}
I wrote here few thoughts looking your code.
Remember to always close the object Reader and Writer.
Have a look at try-with-resources statement :
try (Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true))) {
writer.write(mentionString);
} catch (IOException e) {
// Print error + stacktrace
}
To read an entire file in a List<String>:
List<String> lines = Files.readAllLines(Paths.get("tweets.txt"), StandardCharsets.UTF_8);
And again, I think it's a bad practice write in the same file you're reading of.
I would suggest to write in a different file if you don't have a particular constraint.
But if you really want have this behavior there are few alternative.
Create a temporary file as output and, when you process is successfully completed, than move it to the old one using Files.move(from, to).

Cannot be cast to java.util.ArrayList

Trying to write an object to an array and then save to output.data, then read the objects again.
Writing:
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(arr);
JOptionPane.showMessageDialog(null, "File Written Successfully");
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Reading:
private void readBtnActionPerformed(java.awt.event.ActionEvent evt) {
File inFile;
FileInputStream fStream;
ObjectInputStream oStream;
try {
inFile = new File("output.data");
fStream = new FileInputStream(inFile);
oStream = new ObjectInputStream(fStream);
//create an array of assessments
ArrayList <Assessment> xList;
xList = (ArrayList<Assessment>)oStream.readObject();
for (Assessment x:xList) {
JOptionPane.showMessageDialog(null, "Name: " + x.getName() + "Type: " + x.getType() + "Weighting: " + x.getWeighting());
}
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
} catch (ClassNotFoundException ex) {
System.out.println("Error: " + ex);
}
}
The code comppiles just fine, and the file itself saves alright too. But when I try to read the file nothing happens, and NetBeans says
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Lnetbeansswingexample.Assessment; cannot be cast to java.util.ArrayList"
the line of code giving trouble seems to be
xList = (ArrayList<Assessment>)oStream.readObject();
Any help would be really appreciated, thanks. Sorry if the answers obvious, pretty new to programming.
Based on the exception you got, it looks like oStream.readObject() returns an array of Assessment, not a List. You can convert it to a List:
List <Assessment> xList;
xList = Arrays.asList((Assessment[])oStream.readObject());
or if you must use a java.util.ArrayList :
ArrayList<Assessment> xList;
xList = new ArrayList<> (Arrays.asList((Assessment[])oStream.readObject()));

Using FileWriter to convert Google Analytics data into CSV file using JAVA

Hi all after getting some advice, I am attempting to use the filewriter method in order to export my google analytics queries that i got to a CSV file format here is what i have so far
private static void printGaData(GaData results) {
try {
PrintWriter pw = new PrintWriter(BufferedWriter(new FileWriter("data.csv")));
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println(
"printing results for profile: " + results.getProfileInfo().getProfileName());
if (results.getRows() == null || results.getRows().isEmpty()) {
System.out.println("No results Found.");
} else {
// Print column headers.
for (ColumnHeaders header : results.getColumnHeaders()) {
System.out.printf(header.getName() + ", ");
}
System.out.println();
// Print actual data.
for (List<String> row : results.getRows()) {
for (String column : row) {
pw.printf(row + ", ");
}
pw.println();
}
pw.println();
}
}
}
doesnt output any data and keeps saying that the pw is non extent and stuff like that
Your PrintWriter is inside the try catch block. If you define it outside like
PrintWriter pw = null;
try {
pw = new PrintWriter(BufferedWriter(new FileWriter("data.csv")));
} catch (Exception e) {
// handle exception
}
then it will be available to the rest of your code.

Categories

Resources