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

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

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

File isn't written to after program runs

So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
String save = new String();
while(sc.hasNextLine())
{
save=sc.nextLine();
}
byte buf[]=save.getBytes();
FileOutputStream fos = new FileOutputStream(f);
for(int i=0;i<buf.length;i++)
fos.write(buf[i]);
if(fos != null)
{
fos.flush();
fos.close();
}
}
If anyone has a way to fix the code or even a better idea for saving please let me know, thanks
You are replacing save value in every single nextLine.
Change this line:
save = sc.nextLine();
to this one:
save += sc.nextLine();
Also, it's better to use a FileWriter when you are writing String to a file.
And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
Look at code included below:
public static void main (String[] args) throws Exception
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine())
{
builder.append(sc.nextLine() + "\n");
}
String save = builder.toString();
FileWriter writer = new FileWriter(f);
writer.write(save);
writer.close();
}
Also close() implicitly calls flush().

How Can I Create A File In Java?

I am working on a program that needs a lot of app data. I am trying to create a function that creates a file with the path/file name of the string path. Here's my code:
public static void CreateFile(String path) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.close();
}
What did I do wrong? Shouldn't it create a file?
you can refer to this code :
FileWriter fw = new FileWriter("C:\\FileW3.txt");// you can give path here
//or
FileOutputStream fos = new FileOutputStream("path name");
PrintWriter pw = new PrintWriter (new OutputStreamWriter(fos));
pw.write("Combo stream and writer + using PrintWriter's write() methood/n");
pw.println();
pw.println("now using PrintWriter's println() methood");
pw.flush();
pw.close();
Also
File f = new File("path and filename");
This wont create a file , the file object can be used as parameter in FileWriter or FileOutputStream to create and then write to that file.
File object is just abstract representation of file.
It seems that you want to create an empty file. For this, you can use Files.createFile or File.createNewFile (but it will require you to instantiate a File).
To create a non-empty file, just write something in it and it will be automatically created if it does not exist.
Please see this link in the doucmentation - Create a file object then call 'createNewFile()' method on the newly created object.

Java deletes my file and creates a new one

I am trying to finish a bank accounts homework assignment. I have a text file, "BankAccounts.txt" which is created if there is no file with that name. However, if the file exists, I do not create it. But Java desides to delete all my code inside of it :(. Can you help me identify why this happens? Thanks <3
Code:
static Scanner keyboard = new Scanner(System.in);
static File file;
static PrintWriter Vonnegut; //a great writer
static FileReader Max;
static BufferedReader Maxwell;
public static void main(String[] args) {
initialize();
}
static void initialize(){
try { // creating banking file
file = new File("src/BankAccounts.txt");
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
Max = new FileReader("src/BankAccounts.txt");
Maxwell = new BufferedReader(Max);
//get list of usernames and passwords for later
usernames = new String[countLines() / 5];
passwords = new String[usernames.length];
checkingAccounts = new String[usernames.length];
savingsAccounts = new String[usernames.length];
} catch (IOException e) {
e.printStackTrace();
}
}
And this method keeps returning 0... regardless of whether or not my file has data in it.
static int countLines() throws IOException {
BufferedReader Kerouac = new BufferedReader(Max);
int lines = 0;
while(Kerouac.readLine() != null)
lines++;
Kerouac.close();
System.out.println(lines);
return lines;
}
After I run the program, unless I call a method that writes to the file, all the contents of the file will be gone.
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Redundant. Remove.
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
This always creates a new file, which is why the previous line is redundant. If you want to append to the file when it already exists:
Vonnegut = new PrintWriter(new FileOutputStream("src/BankAccounts.txt", true),"UTF-8");
The true parameter tells the FileOutputStream to append to the file.
See the Javadoc.
Or use a FileWriter instead of a FileOutputStream, same principle.
When you create a PrintWriter it will always delete the file if it already exists, from the javadoc:
... If the file exists then it will be truncated to zero size ...
(i. e. its content will be deleted)
Instead of using FileReader and PrintWriter you need to use a RandomAccessFile to write and/or read your file in this way:
RandomAccessFile myFile = new RandomAccessFile("/path/to/my/file", "rw");
In this way the file is automatically created if it doesn't exist, and if it does, it just opens it.

Appending to a file in java

I am working on a project. For the project I am using GUI and I want to write a number to a file. I have been successful, and I can write the number to the file that i want to. My problem that hopefully someone can give insite to is that everytime i write a number to a file the new number replaces the old one. How would i go about keeping the current info in the file. My code is:
public static void writeCodeFile (String filename, int x, String userName) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.newLine();
outputWriter.write(userName +":"+ Integer.toString(x));
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
}
Use append mode:
outputWriter = new BufferedWriter(new FileWriter(filename, true));
When you create the FileWriter, add a second parameter "true" to go into append mode.

Categories

Resources