After creating file using java, there were no values in it - java

I have created file using java, with following code
String Filecontent= "hei";
creating file
PrintWriter writer=new PrintWriter("D://balanworkspace//Coretest//Corejavatest//src//intvquestest//mydet3_8.txt","UTF-8");
printing the string
System.out.println(Filecontent);
writing to file
writer.println(Filecontent);
when I opened the file, there is no values. Why is it so?

You need to close the PrintWriter by doing this:
writer.close();

Make sure that the complete path of your file exists... If not, create a File and use mkdirs method to create it. After that, write with your PrintWriter
File f = null;
f = new File("yourpath");
Boolean bool = f.mkdirs();

You will need to flush the stream, for the values to appear in the file.
writer.flush()
Closing the stream will invoke the same,
writer.close()
If you don't want to use flush and close, you could pass in an argument "true" to the constructor of PrintWriter which will cause the output to be flushed each time println() is invoked.
PrintWriter(Writer out, boolean autoFlush)

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

How can I deleting the content of a file without deleting it self?

I want to clear the content of a file witch have a specific extension file.tctl, i don't want to change any thing about the file neither deleting it. The file is generated from a specific model checker so that i have just to delete the content and write my own. I tried to print an empty string like that:
PrintWriter writer = new PrintWriter(file.tctl);
writer.print("");
writer.close();
but the file doesn't work any more. So if there's another method to clear the content of the file.
Just remove the print altogether from your code. You've already truncated the file with the new FileOutputStream/PrintWriter/ whatever you use to open it. No I/O or truncate() necessary. Don't use append mode.
Most easy way I guess
new RandomAccessFile("filename.ext", "rw").setLength(0);
Call your write() method like this:
.write((new String()).getBytes());
This will make your file empty. If that doesn't works, try with this:
FileOutputStream erasor = new FileOutputStream("filename.ext");
erasor.write((new String()).toByteArray());
erasor.close();
Or just try to overwrite the file
//open file in override mode
FileOutputStream out = new FileOutputStream("filename.ext");
//now anything that we write here will remove the old one so just write space ("") here
You have to use a FileOutputStream and then you have the truncate() method:
File f = new File("path-of-the-file.here");
FileChannel channel = new FileOutputStream(f, true).getChannel();
channel.truncate(0);
channel.close();

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'.

Write to External File without ending the program

I have a program that is only meant to be terminated by pressing Ctrl + C. In this program I write to an external file using:
File logFile = new File("output.txt");
PrintWriter log_file_writer = new PrintWriter(logFile);
log_file_writer.println("TEXT");
However because I don't know when the program will be terminated, I can't close the file using:
log_file_writer.close();
I think this is resulting in no text appearing in the output file.
Would anyone have a solution for this?
Thank you for your help.
log_file_writer.flush();
will push the content to disk
As the javadoc says:
PrintWriter(File file) Creates a new PrintWriter, without automatic line flushing, with the specified file.
Therefore, you need to flush the data you want to print that is actually buffered:
log_file_writer.flush();
You did not flush the content, I always use the autoFlush argument, but it is not available with File:
PrintWriter log_file_writer = new PrintWriter(new FileOutputStream("output.txt"),true);
but you can also use log_file_writer.flush(); after each write.

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