Java PrintWriter doesn't append to existing .txt file after closing - java

I've run into some problems trying to append to an existing text file.
It doesn't seem to append a line text. So far i've got this method:
public static void addLine(File f, String line) {
try {
FileWriter fw = new FileWriter(f.getName(), true);
BufferedWriter buffer = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(buffer);
pw.println(line);
pw.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
and in my main i've got the following:
public static void main(String[] args) {
File f = new File("adresOfFile");
if (f.exists() && !f.isDirectory()) {
System.out.println("File " + f.getName() + " exists!");
System.out.println("\n" + "Path: " + f.getAbsolutePath());
System.out.println("\n" + "Parent: " + f.getParent());
System.out.println("\n" + "--------------CONTENT OF FILE-------------");
addLine(f, "");
addLine(f, "The line to append");
try {
displayContent(f);
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("File not found");
}
}
When I run the program it doesn't seem to give any errors. Running the program should print out the existing text (displayContent), which is done after appending (addLine). But when I run it, it only shows the existing text, without the appended line.
It doesn't show up in the text file either. I tried to put a System.out.println(); in the method, and it prints, so I know its running the method properly, just not appending.
EDIT AWNSER: replaced f.getName() with f, and added pw.flush before pw.close()

I think that your displayContent(File) function has bugs.
The above code does append to the file.
Have a look at the file to see if anything is appended.
Also do you need to create PrintWriter object each time you append a line?
If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object.

Related

How can I get a variable to read a file and check how many times it contains a word?

I wanted "szSearch" to read the WORDLIST.txt file and check how many times the user's word appears in the file. So for example,
What word are you searching for? long
Searching the file...
The word long appears 24 times in the file WORDLIST.txt.
--- File End ---
public static void main(String[] args)
{
//creating scanner objects which will be used to read in the file
FileReader file = null;
BufferedReader br = null;
//declaring variables and assigning values
Scanner szKeyboard = new Scanner (System.in);
String szWord = "";
String szSearch;
int iCount = 0;
try
{
//open the file WORDLIST.txt using the Scanner and File classes
//File object used to open and store the file
//Scanner object will be used to read through the file object
file = new FileReader("WORDLIST.txt");
//needed for methods
br = new BufferedReader(file);
//ask the user what word they're searching for
System.out.print("What word are you searching for? ");
szWord = szKeyboard.nextLine();
System.out.println("Searching the file...");
szSearch = br.readLine();
//method to count how many times that word occurs in the WORDLIST.txt file
while (szSearch.contains(szWord))
{
iCount = iCount + 1;
}
System.out.println("The word " + szWord + " appears " + iCount + " times in the file WORDLIST.txt.");
}//end try
catch (Exception e)
{
System.out.println("Error - Writing to File: " + e);
}//end catch
finally
{
//close scanner
szKeyboard.close();
//finally runs regardless of wheter the try has worked
//the aim of a finally is to tidy up any loose ends
//if the contents within read is not equal to nothing i.e. it was possible to open and read
//close the file (try) if the file was not loaded catch the exception IOException
try
{
br.close();
`your text` }
catch(IOException e)
{
System.out.println("Error - Closing BufferReader: " + e);
}
try
{
file.close();
}
catch(IOException e)
{
System.out.println("Error - closing FileReader: " + e);
}
System.out.println("\n\n--- File End ---");
}//end try catch finally`
}//end class
This is what I tried doing but when I run it, it says:
What word are you searching for? long
Searching the file...
The word long appears 0 times in the file WORDLIST.txt.
--- File End ---
Try replacing the while you have with this block of code, it probably requires some tweaking as I didn't test the code, but the logic I think solves it.
while ((strCurrentLine = objReader.readLine ())! = null) {
List<String> words = Arrays.asList(strCurrentLine.split(" "));
iCount += words.stream().hasMatch(w -> w.equals(szWord)).count();
}

Need help loading in a file that contains Strings and a Collection<String>?

I have two methods, one for writing information a textfile and one for reading in that same text file. I have the writing method working which writes various String objects and a Collection to the file. The problem comes when loading or reading the same file? I don't quite know how to read in the Collection of notes from the file? Here are both my methods.
public void writeDvd() throws DVDLibraryException {
PrintWriter out;
try {
out = new PrintWriter(new FileWriter(LIBRARY));
} catch (IOException ex) {
throw new DVDLibraryException("Problem writing to file", ex);
}
List<DVD> dvdList = this.returnListDvds();
for (DVD currentDvd : dvdList) {
out.print(currentDvd.getTitle() + DELIMETER
+ currentDvd.getReleaseDate() + DELIMETER
+ currentDvd.getRating() + DELIMETER
+ currentDvd.getDirectorsName() + DELIMETER
+ currentDvd.getStudio() + DELIMETER
+ currentDvd.getNotes());
out.flush();
}
out.close();
}
And here is my loadDVD() method:
public void loadDvd() throws DVDLibraryException {
Scanner sc;
try {
sc = new Scanner(new BufferedReader(new FileReader(LIBRARY)));
} catch (FileNotFoundException ex) {
throw new DVDLibraryException("Could not read file", ex);
}
String currentLine;
String[] currentTokens;
while (sc.hasNext()) {
currentLine = sc.nextLine();
currentTokens = currentLine.split(DELIMETER);
DVD currentDvd = new DVD(currentTokens[0], currentTokens[1],
currentTokens[2], currentTokens[3], currentTokens[4]);
//I'm trying to do above with the currentTokens[5] for the Collection of Strings but not sure how to approach the problem?
//This does not work
//Collection<String> notes = currentDvd.getValuesNotes();
//currentDvd.setValuesOfNotesForReading(notes);
//String s = String.join(DELIMETER, notes);
//currentDvd.setValuesOfNotesForReading(s);
dvds.put(currentDvd.getTitle(), currentDvd);
}
sc.close();
}
Assuming DELIMITER is not a newline and your intent is to write all the fields in one row, you seem to be missing an out.println() after the out.print().

Adding printlines and text to FileWriter (writer.write)

I was wondering how to add print lines to a filewriter output.
At the moment when the full code has run and I open the .txt folder it looks like this
https://gyazo.com/b287d61eafb100dce1ce2476b71623e9
I was wondering how I could add text and printlines to make the format similar to this : https://i.gyazo.com/def6e157e24dc0ed0fe68e1509152405.png
try
{
FileWriter writer = new FileWriter("Gamer Report Data.txt");
writer.write(gamerName);
writer.write(System.getProperty( "line.separator"));
writer.write(gamerReport);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
Like this:
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
//This line will split the gameReport string by the ':' separator
//Into an array of strings.
string[] report = gameReport.split(":");
//Edit here with regards to latest comment
//This will print the game score if the reports array has data.
if(report == null) {
writer.println("Game report was null.");
} else if(report.length == 3) {
writer.println("Game:" + report[0]+", score=" + report[1] +", minutes played="+ report[2]);
}
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
Is it what you want? just similar to second picture.
import java.io.FileWriter;
import java.io.IOException;
//if your java file name is ABC.java then your class name is ABC
public class ABC
{
public static void main(String[] args) throws IOException
{
String text = "Name here";
String text2 = "Data here";
FileWriter fw = new FileWriter("Output.txt");
fw.write(text);
fw.write(System.lineSeparator());
if(text.length()>text2.length())
for(int i=0;i<text.length();i++) fw.write("-");
else
for(int i=0;i<text2.length();i++) fw.write("-");
fw.write(System.lineSeparator());
fw.write(text2);
fw.close();
}
}

Is this correctly writing to a text file?

I am trying to save the integers in an array to a text file. Neither of these seem to be doing the trick while sitting in my main method and I was wondering if someone could point out my mistake.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File ("C:/Users/Usman/Desktop/directory/scores.txt");
PrintWriter writer = new PrintWriter("scores.txt");
writer.println("Player 1 score: " + scorep1[0]);
writer.println("Player 2 score: " + scorep1[1]);
writer.println("Player 3 score: " + scorep1[2]);
writer.println("Player 4 score: " + scorep1[3]);
writer.close();
System.exit(0);
}
No score.txt file is created on my desktop in either of these attempts.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File("C:/Users/Me/Desktop/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
System.exit(0);
}
EDIT: This is what I have made of the answers so far, please feel free to edit the wrong bit so I can clearly see what I've missed.
System.out.println("What's happening");
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
FileWriter fileWriter = new FileWriter(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
Also what about this:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Rather a problem of directory
see this:
How to use PrintWriter and File classes in Java?
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
// NOK for C:/Users see below
// File file = new File("C:/Users/Me/Desktop/file.txt");
File file = new File("C:/classical_dir/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
This works well on my pc:
File file = new File("C:/foo/bar/blurps/file.txt");
This throws an exception: windows seems not to want it
File file = new File("C:/Users/Me/Desktop/file.txt");
because, C:/Users/Me seems to be prohibited: C:/Users seems to be protected by system
see this for writing in User directory: how can I create a file in the current user's home directory using Java?
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
see this also: How to get the Desktop path in java
Because File object does not create a physical copy of a file. For details follow this linkDoes creating a File object create a physical file or touch anything outside the JVM?
Now if we come to your solution then first make a empty file on the disk by following command
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "C:\\Users\\MOSSAD\\Desktop\\new\\temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
File file = new File (fileName);
PrintWriter writer = new PrintWriter(file);
writer.println("Player 1 score: " + 5);
writer.println("Player 2 score: " + 2);
writer.println("Player 3 score: " + 3);
writer.println("Player 4 score: " + 4);
writer.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
you need to use double slash in path .link

Buffered Writer overwriting file when not wanted

I have this code here that takes in 3 arguments, A Directory, a Filename, and a number. The program creates the filename in the directory and writes the number in it. So I can say...
>java D: myName.txt Clay 100
which will create a file named myName.txt in D: and says 100 in it.
If myName is taken up, it changes the name to myName(2), then myName(3) (if myName(2) taken up). The only problem is that when it changes the name to myName(2) and writes, it overwrites myName. I dont want it to overwrite myName, I want it to just create a new file with that name. Ive looked at similar questions and the common answer is the flush and close the writer which ive done And it still doesnt work.
Any help would be appreciated, here is my code so fart...
import java.io.*;
public class filetasktest{
public static void main(String[] args) throws IOException{
int i = 2;
String directory = args[0];
if (directory.substring(directory.length() - 1) != "/"){
directory += "/";
}
String contactName = args[1];
String contactNumber = args[2];
String finalDirectory = directory + contactName + ".contact";
File f = new File(finalDirectory);
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(finalDirectory), "utf-8"));
writer.write(contactNumber);
} catch (IOException ex){
System.out.println(ex.getMessage());
} finally {
try {
writer.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
You need to use append mode
new BufferedWriter(new FileWriter(yourFileName, true));
here, true means that the txt should be appended at the end of file.
Check the FileWriter javadoc for more information.
Your problem is here:
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
The renameTo method does not change the path of a File object; it renames a file on disk. The path of f stays the same throughout the loop: it starts out as D:/myName.txt and if a file by that name exists, the file is renamed as D:/myName(1).txt. The variable f still holds the path D:/myName.txt, which no longer names a file, and the content is written to D:/myName(1).txt, overwriting the previous content.
To fix this issue change the loop to:
while (new File(finalDirectory).exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
i++;
}
Take a look at FileInputStream(String, boolean) which will allow you to flag if the file should be appended or overwritten

Categories

Resources