Trouble with filewriter overwriting files instead of appending to the end - java

OK, I'm having some trouble writing multiple lines to a text file.
the program runs, but it won't use new lines each time
when I want it run 4 times, the text file should look like:
a
b
c
d
instead, it looks like:
d
who knows how to fix this problem? all imports are correctly imported.
source(it's been slightly edited, assume everything is properly defined):
import java.io.*;
public class Compiler {
public static void main (String args[]) throws IOException
{
//there's lots of code here
BufferedWriter outStream= new BufferedWriter(new FileWriter("output.txt"));
outStream.newLine();
outStream.write(output);
outStream.close();
}
}

Make sure that when you create an instance of a FileWriter, that you are appending to the end of it. This can be done by using this specific FileWriter constructor which takes an additional boolean as a second parameter. This boolean tells the FileWriter to append to the end of the file, rather than overwriting the file.
BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true));

By default FileWriter will overwrite the file. What you might want to do is define the reader in the following manner:
new FileWriter("encoded.txt", true)
This way the file will be appended to instead of being overwritten.
Hope this helps!

I'm not sure what this code is supposed to do. It throws an error if your input string is more than one character long, because you close your FileWriter inside the loop, then try to write to it again.
I'm interpreting your question the following way: you're wondering why only the most recent output is in the file. In that case, it's because you didn't create your FileWriter in append mode. Look at the different constructors available for FileWriter, and use the one that allows you to append to the file.

Related

How to use tables and .txt in Java?

Im building a Car Rental program and what I want it to, for now, is:
Register a user
Register a car
using .txt files to store the data.
With the code I've written, I can register only a single car and user. Every time I run the register method for client or car, the last register is erased.
Can you help me with this? Also, later I'm going to implement a way to rent a car, but I don't know how to do that also, so if you have any ideas of how to do it, please tell me!
Also I intend to do it without SQL or such things.
This is the code I'm using to register a user (I'm using netbeans with JForm):
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nomeClient = txtNomeClient.getText();
String idClient = txtIdClient.getText();
File file = new File("clients.txt");
try {
PrintWriter output = new PrintWriter(file);
output.println(nomeClient);
output.println(idClient);
output.close();
JOptionPane.showMessageDialog(null, "Client registed!");
} catch (FileNotFoundException e) {
}
}
The problem is that you overwrite the existing file clients.txt, instead of appending to it by calling new PrintWriter(file). You can use the following code:
FileWriter fileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(fileWriter));
This way, you append the end of the file, see the constructor FileWriter(File file, boolean append). The documentation describes it perfectly:
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
The FileWriter is just used to open a file in append mode, as PrintWriter does not have a suitable constructor to do that directly. You could also write characters with it, but a PrintWriter allows for formatted output. From the documentation of FileWriter:
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
The PrintWriter uses the FileWriter passed in its constructor to append to the destination file, see here for a good explanation. As stated there, you could also use an FileOutputStream. There are multiple ways to do this.
Here is an example using a FileOutputStream and a BufferedWriter, which supports buffering and can reduce unnecessary writes that penalize performance.
FileOutputStream fileOutputStream = new FileOutputStream("clients.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileOutputStream);
PrintWriter printWriter = new PrintWriter(bufferedWriter);

Splitting a text file

I have this text file of the format:
Token:A1
sometext
Token:A2
sometext
Token:A3
I want to split this file into multiple files, such that
File 1 contains
A1
sometext
File 2 contains
A2
sometext
I do not have much idea about any programming or scripting language as such, what would be the best way to go about the process? I was thinking of using Java to solve the problem.
if you want to use java, I would look into using Scanner in conjunction with File and PrintWriter with a for loop and some exception handling you will be good to go.
import the proper libraries!
import java.io.*;
import java.util.*;
declare the class of course
public class someClass{
public static void main(String [] args){
now here's where stuff starts to get interesting. We use the class File to create a new file that has the name of the file to be read passed as a parameter. You can put whatever you want there whether its a path to the file or just the file name if its in the same directory as your code.
File currentFile = new File("new.txt");
if (currentFile.exists() && currentFile.canRead()){
try{
next we create a scanner to scan through that newly created File object. the for loop continues on as long as the file has new tokens to scan through. .hasNext() returns true only if the input in the scanner has another token. PrintWriter writes and creates the files. I have it set that it will create the files based on the iteration of the loop (0,1,2,3 etc) but that can be easily changed. (see new PrintWriter(i + ".txt". UTF-8); )
Scanner textContents = new Scanner(currentFile);
for(int i = 0; textContents.hasNext(); i++){
PrintWriter writer = new PrintWriter(i + ".txt", "UTF-8");
writer.println(textContents.next());
writer.close();
}
these catch statements are super important! Your code wont even compile without them. If there is an error they will make sure your code doesn't crash. I left the inside of them empty so you can do what you see fit.
} catch (FileNotFoundException e) {
// do something
}
catch (UnsupportedEncodingException i){
//do something
}
}
}
}
and thats pretty much it! if you have any questions be sure to comment!
There is no best way and it depends on your environment and need actually. But for any language figure out your basic algorithm and try using the best available data structure(s). If you are using Java, consider using guava splitter and do look into its implementation.

Java - Working with IO - Clarification

I am working on a few lessons in Java, and the instructor started introducing how IO working in Java. I just have a couple of question that an experience Java programmer could clarify.
The piece of code below is a program that creates a (notepad) text file in the same file directory I am writing my code. After that, it simply prints basic lines of text to that file.
import java.io.FileWriter; //Imports Filewriter class
import java.io.PrintWriter; //Imports PrintWriter class
import java.io.IOException; //Imports IOException
public class Chap17Part2
{
public static void main(String[] args) throws IOException
{
String fileName = "grades.txt"; //Creating name for file
PrintWriter outFile = new PrintWriter(new FileWriter(fileName)); //Question 1
outFile.println(85); //Prints to file
outFile.println(77); //Prints to file
outFile.close(); //Ends buffer, and flushes data to file.
}
}
Question 1: Due to only brief explanations by the instructor, this line of code is a bit confusing to me. I know that in this line, we are creating the "outFile" object. After that, we are calling the PrintWriter constructor, and inside its parameters, we are calling the constructor for FileWriter. Inside of its constructor, we are calling the name of the file we created as a String. That is the confusing part. I'm not understanding exactly what PrintWriter, and FileWriter are doing. It looks like FileWriter is creating our file, and PrintWriter is giving us the println() method to print the two numbers to the file. After doing research, I have found that you can pretty much achieve the same purpose with both FileWriter, and PrintWriter. What is the purpose for teaching file processing in this manner, and what exactly are the two classes doing? Thank you for the help in clarifying this for me!
The code is equivalent to
FileWriter fw = new FileWriter(fileName);
PrintWriter outFile = new PrintWriter(fw);
So it first creates a FileWriter, which writes characters to a file, and then creates a PrintWriter which prints its values to the FileWriter.

Clear contents of a file in Java using RandomAccessFile

I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile is not working, and I don't understand why. Here is the basic outline of my code.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:(Lets imagine that the program looped twice before clearCondition was met)
Example Text
Example Text
Text to be written onto the first line of temp file
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.
What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.

How to write more than once to text file using PrintWriter

I know how to create a PrintWriter and am able to take strings from my gui and print it to a text file.
I want to be able to take the same program and print to the file adding text to the file instead of replacing everything already in the text file. How would I make it so that when more data is added to the text file, it is printed on a new line every time?
Any examples or resources would be awesome.
try
{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).
Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));
writer.println("abc");
FileWriter constructor comes with append attribute,if it is true you can append to a file.
check this
Your PrintWriter wraps another writer, which is probably a FileWriter. When you construct that FileWriter, use the constructor that takes both a File object and an "append" flag. If you pass true as the append flag, it'll open the file in append mode, which means that new output will go at the end of the file's existing contents, rather than replacing the existing contents.

Categories

Resources