Replace text in text file java

Replacing text in a file using java

I have a text file named FormatString.java. It contains a few words. OUt of those words, I want to replace the word oldstring with newstring and rename the final result as t.txt . I have written the code. Technically it should work. The problem is that I dod not know where to save the FormatString.java file. Do I save it in the same class folder where the program ReplacingText is saved or do I save it somewhere else. I go to the command prompt and into the folder where the ReplacingText.class and the FormatString.java file is saved and type the below statement: java ReplacingText FormatString.java t.txt oldstring newstring

package replacingtext; import java.io.*; import java.util.*; public class ReplacingText < public static void main(String[] args) throws Exception < if (args.length !=4) < System.out.println( "Usage: java ReplaceText sourceFile targetFile oldStr newStr"); System.exit(0); >File sourceFile = new File(args[0]); if(!sourceFile.exists()) < System.out.println("Source file " + args[0]+" does not exist"); System.exit(0); >File targetFile = new File(args[1]); if (targetFile.exists()) < System.out.println("Target File " + args[1] + "already exist"); System.exit(0); >Scanner input = new Scanner(sourceFile); PrintWriter output2 = new PrintWriter(targetFile); while (input.hasNext()) < String s1=input.nextLine(); String s2=s1.replaceAll(args[2],args[3]); output2.println(s2); >input.close(); output2.close(); > > 

1 Answer 1

If you are running the program from command line, maybe you wan to put the FormatString.java in your bin folder.

ProjectRootFolder bin FromatString.java ReplacingText.class src ReplacingText.java 
ProjectRootFolder build classes FromatString.txt replacinttext ReplacingText.class src ReplacingText.java 

C:\Users\Dhaval\Desktop\Java Assignment\ReplacingText\build\classes>java replacingtext.ReplaceText FormatString.java public private

Try to run the program like I have above with all the files in the same Directorys like I have

Читайте также:  Html url link forum

Источник

Replacing an old textfile with a new textfile in Java

I was just wondering how I would go about replacing a certain bit of a text in a textfile in Java? For example if I had a text file with the following contents:

John: My Status is: 0; William: My Status is: 0; Andrew: My Status is: 1; Bob: My Status is: 1; Smith: My Status is: 0; 

And I wanted to replace the line containing the string «William» with «William: My Status is: 1;» So, the new textfile should look like this:

John: My Status is: 0; William: My Status is: 1; Andrew: My Status is: 1; Bob: My Status is: 1; Smith: My Status is: 0; 
  1. Read through the file line by line. Write and Append each line to a new temporary text file.
  2. If the line contains the word «William», then replace the line with «William: My status is: 1» and then append to the temporary text file.
  3. Replace my old textfile with the temporary text file

Now the bit I’m stuck at is step 3! (The step I thought would be the easiest!).

It seems the content gets written correctly to the temporary textfile, but for some reason I can’t get it to replace the old textfile! This is my actual code so far: (Sorry if its too much to read, if it is then if you could just give me some general advice that would be great too!)

public void verifyUser(UserDataObject u) < String eachline = ""; String uname = u.getUsername(); Scanner sc; try < File file1 = new File("FlatFileStorage.txt"); sc = new Scanner(file1); FileWriter fw = new FileWriter("TempFlatFileStorage.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw); while (sc.hasNextLine()) < eachline = sc.nextLine(); if ( eachline.contains(uname) ) < int lineStart = eachline.indexOf("Username: " + uname); int lineEnd = eachline.indexOf("end" + uname + ";"); int unameLength = uname.length(); String lineStatus = eachline.substring(lineStart, lineEnd + 4 + unameLength); //System.out.println(lineStatus); String newLineStatus = lineStatus.replace("VerifyStatus: 0", "VerifyStatus: 1"); System.out.println(newLineStatus); out.println(newLineStatus); >else < System.out.println(eachline); out.println(eachline); >> out.close(); > catch (FileNotFoundException e) < System.out.println("Error: Could not find database/storage."); >catch (IOException e) < System.out.println("There has been an error: " + e.getMessage()); e.printStackTrace(); >File file = new File("FlatFileStorage.txt"); File tempfile = new File("TempFlatFileStorage.txt"); tempfile.renameTo(file); > 

Источник

Replace first line of a text file in Java

I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I’d rather not have to loop over everything, so I’m wondering if there is another way to do this. I’d also like to apply some rules to the first line so that I replace instances of certain words with other words. Is this possible?

5 Answers 5

A RandomAccessFile will do the trick, unless the length of the resulting line is different from the length of the original line.

If it turns out you are forced to perform a copy (where the first line is replaced and the rest of the data shall be copied as-is), I suggest using a BufferedReader and BufferedWriter . First use BufferedReader ‘s readLine() to read the first line. Modify it and write it to the BufferedWriter . Then use a char[] array to perform a brute-force copy of the remainder of the file. This will be more efficient than doing the copy line by line. Let me know if you need details..

Another option is to perform the reading and writing inside the same file. It’ll be a bit more complex though. 🙂 Let me know if you need details on this as well..

Can you pls provide some info if the length of the string to be replaced is different. Is it possible without copying to a new file

If the length is different you will at the very least have to re-write all bytes, either in the same file or in a different file.

Источник

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

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)

Источник

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