Java FileWriter refusing to overwrite - java

I'm very confused...
public class Testing {
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
System.out.println("Testing overwrite");
FileWriter writer = new FileWriter("c:\\testing\\testfile.txt", false);
writer.write("First test");
writer.flush();
TimeUnit.SECONDS.sleep(5);
writer.write("Second test");
writer.flush();
writer.close();
}
}
After completion, the contents of the file is:
First testSecond test
The boolean passed to the FileWriter with the value of False should be causing an overwrite, not an append, according to the Java docs here: Java 6 Filewriter API
I've had this problem in the past, and I've used a RandomAccessFile to bypass the problem, but now it's just annoying me!
Any ideas or suggestions would be greatly appreciated, thanks!

When calling
FileWriter writer = new FileWriter("c:\\testing\\testfile.txt", false); it will overwrite the file. It won't overwrite per .write. The option only applies for the contructor.

Related

How to create and output to files in Java

My current problems lie with the fact that no matter what solution I attempt at creating a file in Java, the file never, ever is created or shows up.
I've searched StackOverflow for solutions and tried many, many different pieces of code all to no avail. I've tried using BufferedWriter, PrintWriter, FileWriter, wrapped in try and catch and thrown IOExceptions, and none of it seems to be working. For every field that requires a path, I've tried both the name of the file alone and the name of the file in a path. Nothing works.
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
I don't get any errors thrown whenever I've run my past code, however, the files never actually show up. How can I fix this?
Thank you in advance!
There are several ways to do this:
Write with BufferedWriter:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
If you want to append to a file:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
Using PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Using FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Note:
If you try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown.
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it.
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream.
Source and More Examples: https://www.baeldung.com/java-write-to-file
Hope this helps. Good luck.
A couple of things worth trying:
1) In case you haven't (it's not in the code you've shown) make sure you close the file after you're done with it
2) Use a File instead of a String. This will let you double check where the file is being created
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
As a bonus, Java's try-with-resource will automatically close the resource when it's done, you might want to try
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}

Getting an IO Exception when creating a file and writing in to it using FileWriter

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandling1 {
public static void main(String[] args){
try{
File file = new File("FileHandlingExample1.txt", "US-ASCII");
FileWriter writer = new FileWriter(file);
writer.write("This is the first line.");
writer.write("This is the seccond line.");
writer.write("This is the third line.");
writer.flush();
writer.close();
}catch(IOException exception){
System.out.print("This is an IO Exception");
}
}
}
Output :- This is an IO Exception.
I am new to File Handling in Java. There are no errors in the program. It gives an IO Exception. Why is that?
I don't know exactly the path where it is located your file but this is probably wrong :
File file = new File("FileHandlingExample1.txt", "US-ASCII");
It means your file US-ASCII has as parent folder : FileHandlingExample1.txt.
This is the File constructor that you are using :
public File(String parent, String child)
You probably reversed the order of arguments.
And this statement :
FileWriter writer = new FileWriter(file);
throws an IOException if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
This code smells because you dont expose what actually going wrong, you hide information about exception and simple print "bad things happen" you need to print stack trace of your exception and you will be see what actually happen.
Perhaps you file doesn't exist yet, you need to create it before doing something with it, also pay attention how dou you create file, you need only path, before use something will be great to read javadocs File class javaodoc
public class FileHandling1 {
public static void main(String[] args){
try{
File file = new File("FileHandlingExample1.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("This is the first line.");
writer.write("This is the seccond line.");
writer.write("This is the third line.");
writer.flush();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

How to Write to line by line in a single file on different methods in java [duplicate]

This question already has answers here:
Java FileWriter with append mode
(4 answers)
Closed 6 years ago.
I would like to write in a single file in java but in different methods. I wrote this
import java.io.*;
public class Test {
public static File file = new File("text.log");
public static void main (String [] args) throws IOException
{
FileWriter input= new FileWriter(file);
input.write("hello");
input.write("\n");
input.close();
test();
}
public static void test() throws IOException
{
FileWriter input= new FileWriter(file);
input.write("world");
input.write("\n");
input.close();
}
}
The output is just world. It looks like calling the function test() overwrites what was previously written.
You need to open the FileWriter in append mode by passing true as the second argument:
public static File file = new File("text.log", true);
From the Javadoc:
public FileWriter(String fileName, boolean append)
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.
When you write new FileWriter(file, true), it will append instead of overwrite.

Java Random Access File strange characters

So I am using the following code to write to a file in Java, the text prints fine, but it has strange characters between the letters.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeChars("#Minecraft server properties");
configFile.close();
}
I was searching for answer and everything pointed to incorrect usage of writeUTF() so I decided to try that instead which semi-fixed the issue, but I still have that character at the beginning of the line.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeUTF("#Minecraft server properties");
configFile.close();
}
My questions are: what is that char? Vim shows it as an # and what can I do to remove it?
That char is related with the encoding of the file you are creating.
Try using the following code instead:
public static void createConfigFile() throws IOException {
FileWriter writer = new FileWriter("PATH_TO_YOUR_CONFIG_FILE", false);
writer.append("#Minecraft server properties");
// Append any other content you need here.
writer.flush();
writer.close();
}
Hope that helps!

Java - How to Clear a text file without deleting it?

I am wondering what the best way to clear a file is. I know that java automatically creates a file with
f = new Formatter("jibberish.txt");
s = new Scanner("jibberish.txt");
if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank?
Here is what I was thinking:
public void clearFile(){
//go through and do this every time in order to delete previous crap
while(s.hasNext()){
f.format(" ");
}
}
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps
You could delete the file and create it again instead of doing a lot of io.
if(file.delete()){
file.createNewFile();
}else{
//throw an exception indicating that the file could not be cleared
}
Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :
File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);
If you want to clear the file without deleting may be you can workaround this
public static void clearTheFile() {
FileWriter fwOb = new FileWriter("FileName", false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
Edit: It throws exception so need to catch the exceptions
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
type
new PrintWriter(PATH_FILE).close();
Better to use this:
public static void clear(String filename) throws IOException {
FileWriter fwOb = new FileWriter(filename, false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}

Categories

Resources