Java how to rewrite file

How to overwrite a line in a .txt file using Java?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.

The java.util class (constructor) accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. To read various datatypes from the source using the nextXXX() methods provided.

The StringBuffer class is a mutable alternative to String, after instantiating this class you can add data to it using the append() method.

Procedure

To overwrite a particular line of a file −

Read the contents of a file to String −

  • Instantiate the File class.
  • Instantiate the Scanner class passing the file as parameter to its constructor.
  • Create an empty StringBuffer object.
  • add the contents of the file line by line to the StringBuffer object using the append() method.
  • Convert the StringBuffer to String using the toString() method.
  • Close the Scanner object.

Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters.

Rewrite the file contents −

  • Instantiate the FileWriter class.
  • Add the results of the replaceAll() method the FileWriter object using the append() method.
  • Push the added data to the file using the flush() method.

Example

import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class OverwriteLine < public static void main(String args[]) throws IOException < //Instantiating the File class String filePath = "D://input.txt"; //Instantiating the Scanner class to read the file Scanner sc = new Scanner(new File(filePath)); //instantiating the StringBuffer class StringBuffer buffer = new StringBuffer(); //Reading lines of the file and appending them to StringBuffer while (sc.hasNextLine()) < buffer.append(sc.nextLine()+System.lineSeparator()); >String fileContents = buffer.toString(); System.out.println("Contents of the file: "+fileContents); //closing the Scanner object sc.close(); String oldLine = "No preconditions and no impediments. Simply Easy Learning!"; String newLine = "Enjoy the free content"; //Replacing the old line with new line fileContents = fileContents.replaceAll(oldLine, newLine); //instantiating the FileWriter class FileWriter writer = new FileWriter(filePath); System.out.println(""); System.out.println("new data: "+fileContents); writer.append(fileContents); writer.flush(); > >

Output

Contents of the file: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. No preconditions and no impediments. Simply Easy Learning! new data: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. We don’t force our readers to sign up with us or submit their details either. Enjoy the free content

Источник

Читайте также:  Задача удалить каждый третий символ python

How to overwrite an existing .txt file

Methods that may be of interest to you would be: — Returns the current file offset — advances the file offset by — writes to current file position Hope this helps Question: The boolean indicates whether to append or overwrite an existing file.

How to overwrite an existing .txt file

I have an application that creates a .txt file. I want to overwrite it. This is my function:

try< String test = "Test string !"; File file = new File("src\\homeautomation\\data\\RoomData.txt"); // if file doesnt exists, then create it if (!file.exists()) < file.createNewFile(); >else < >FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(test); bw.close(); System.out.println("Done"); >catch(IOException e)

What should I put in the else clause, if the file exists, so it can be overwritten?

You don’t need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :

  • default mode, which overwrites the whole file
  • append mode (specified in the constructor by a boolean set to true ) which appends the new data to the existing one

You don’t need to do anything, the default behavior is to overwrite.

No clue why I was downvoted, seriously. this code will always overwrite the file

Just call file.delete() in your else block. That should delete the file, if that’s what you want.

FileWriter(String fileName, boolean append) 

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

The Below one line code will help us to make the file empty.

FileUtils.write(new File("/your/file/path"), "") 

The Below code will help us to delete the file .

Java — How to overwrite one property in .properties, The Properties API doesn’t provide any methods for adding/replacing/removing a property in the properties file. The model that the API supports is to load all of …

In Java, how do I overwrite a specific part of a line in a file? [duplicate]

I have a csv file thats formatted like this id,text . Here is an example:

helloText,How are you goodbyeMessage,Some new text for a change errorMessage,Oops something went wrong 

Now lets say for example I want to edit the text part of goodbyeMessage which is Some new text for change , to See you later

The resulting csv should then look like this:

helloText,How are you goodbyeMessage,See you later errorMessage,Oops something went wrong 

I have code that can write to the file but when the code finishes executing, this is the resulting csv file:

helloText,How are you goodbyeMessage,Some new text for a change errorMessage,Oops something went wronggoodbyeMessage,See you later 

I know this is occurring because I set the FileWriter’s append value to true . If I don’t everything gets wiped.

I have tried using FileWriter.newLine() to make it look better but that is not what I am trying to achieve. I still want the same number of line in the file. MyApp.java

public static void main(String[] args) throws FileNotFoundException, IOException
/** * Updates the text of a given element in the properties file. * * @param id The id of the element * @param newText The text that will replace the original text. * * @throws IOException If I/O error occurs */ public void updateElementText(String id, String newText) throws IOException < Assertions.checkNotNull(id, "Id must not be null."); Assertions.checkNotNull(id, "Id must not be an empty string."); File file = new File(pathName); BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter wr = new BufferedWriter(new FileWriter(file, true)); try < String line; while((line = br.readLine()) != null) < if(line.contains(id)) < //returns true System.out.println("Is line there: " + line.contains(id)); //returns helloText System.out.println("ID: " + extractId(line)); //returns How are you System.out.println("TEXT: " + extractText(line)); //returns Some new text for a change System.out.println("NEW_TEXT: " + newText); // This is where I am trying to replace the old text // with new text that came from the main method. line = line.replaceAll(extractText(line), newText); //wr.newLine(); wr.write(line); >> > catch(IOException e) < e.printStackTrace(); >finally < wr.close(); >> /** * Gets the id part of a line that is stored in the * properties file. * * @param element The element the id is got from. * @return String representation of the id. */ private static String extractId(String line) < final int commaOccurence = getFirstCommaOccurrence(line); return line.substring(0, commaOccurence); >/** * Gets the text part of a line that is stored in the * properties file. * * @param element The element the text is got from. * @return String representation of the text. */ private static String extractText(String line) < final int commaOccurence = getFirstCommaOccurrence(line); return line.substring(commaOccurence + 1, line.length()); >/** * Gets the first occurrence of a comma in any given line of a text file. * @param element * @return */ private static int getFirstCommaOccurrence(String line)

You just said it. Do not set the FileWriter to true (as it then only appends new stuff). You need to read the whole file, save all lines (for example in a List ). Then you manipulate the data. And after that you rewrite the whole text (for example by using the said List ).

Читайте также:  Таблица для телефона html

In your above code this would be first replace true with false :

BufferedWriter wr = new BufferedWriter(new FileWriter(file, false)); 

Second , always write to the file, as other lines would then get lost:

if(line.contains(id)) < . line = line.replaceAll(extractText(line), newText); >wr.write(line); 

However, if you have a very big file and don’t want to rewrite all lines, then you can go for a more low-level FileWriter , like RandomAccessFile . This concept allows you to start the file manipulation at a given position without rewriting everything that was before this position. You can search the line (or jump, if you know where), make your change. But you will need to rewrite everything that comes after the change. Here’s an usage example: RandomAccessFile example

There is no better solution as this is platform dependent. More specific, it depends on the used Filesystem , for example NTFS or FAT32 and so on.
In general, they store a file by splitting it into several packages. The packages then get saved all over your hard drive, it puts them where they best fit in. The file system saves a pointer to each start package of a file in a master table . Every package then saves a pointer to the next packages and so on until EOF is reached.

You see, it is easy to change something in the middle without changing everything that was before. But you probably need to change the stuff that comes after, as you can not control how the OS splits the new data into packages. If you go very low-level , you may control a single packages and inject data without changing everything after. But I don’t think that you want to do this 🙂

Читайте также:  Вывод даты sql php

Unfortunately, there isn’t really a way to do this (that I know of) besides loading all the file data into some mutable object, and then writing it all back to the file.

The Files class provides a convenient method for reading an entire file into a List

As @Zabuza mentioned in the comments, Java provides a class called RandomAccessFile , which can navigate to a specific place in a file and overwrite bytes. Methods that may be of interest to you would be:

  • getFilePointer() — Returns the current file offset
  • seek(long pos) — advances the file offset by pos
  • write(byte[] b) — writes b to current file position

Is this the best way to rewrite the content of a file in Java?, Unless you’re just adding content at the end, it’s reasonable to do it that way. If you are appending, try FileWriter with the append constructor. A slightly better …

Java create a new file, or, override the existing file

What I want to achieve is to create a file regardless of whether the file exists or not.

I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile() ?

Or is there a clearer way of doing it?

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file . Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file 

You can use a suitable Writer :

BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"))); br.write("some text"); 

It will create a file abc.txt if it doesn’t exist. If it does, it will overwrite the file.

You can also open the file in append mode by using another constructor of FileWriter:

BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true)); br.write("some text"); 

The documentation for above constructor says:

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.

Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:

File f = new File("myfile.txt"); if (f.createNewFile()) < // If there wasn't a file there beforehand, there is one now. >else < // If there was, no harm, no foul >// And now you can use it. 

Java — filewriter overwriting the file, java file overwrite filewriter. Share. Improve this question. Follow edited Oct 17, 2017 at 14:08. ROMANIA_engineer. 51.2k 26 26 gold badges 196 …

Источник

Оцените статью