0

I'm writing a program with a text file in java, what I need to do is to modify the specific string in the file. For example, the file has a line(the file contains many lines)like "username,password,e,d,b,c,a" And I want to modify it to "username,password,f,e,d,b,c" I have searched much but found nothing. How to deal with that?

2
  • 1
    Can you share the code that you tried?? Commented Nov 1, 2020 at 8:22
  • I would like to do so but I didn't figure out any method about how to replace the specific String in the file lol. Commented Nov 1, 2020 at 8:25

4 Answers 4

2

In general you can do it in 3 steps:

  1. Read file and store it in String
  2. Change the String as you need (your "username,password..." modification)
  3. Write the String to a file

You can search for instruction of every step at Stackoverflow.

Here is a possible solution working directly on the Stream:

public static void main(String[] args) throws IOException {

    String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
    String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";

    try (Stream<String> stream = Files.lines(Paths.get(inputFile));
            FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
        stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
            try {
                fop.write(line.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try like this: First, read the file line by line and check each line if the string you want to replace exists in that, replace it, and write the content in another file. Do it until you reach EOF.

import java.io.*;

public class Files {

    void replace(String stringToReplace, String replaceWith) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("/home/asn/Desktop/All.txt"));
        BufferedWriter out = new BufferedWriter(new FileWriter("/home/asn/Desktop/All-copy.txt"));

        String line;

        while((line=in.readLine())!=null)  {
            if (line.contains(stringToReplace))
                    line = line.replace(stringToReplace, replaceWith);
                out.write(line);
                out.newLine();
        }
        in.close();
        out.close();
    } 

    public static void main(String[] args) throws IOException {
        Files f = new Files();
        f.replace("amount", "@@@@");
    }
}

If you want to use the same file store the content in a buffer(String array or List) and then write the content of the buffer in the same file.

Comments

0

If your file look similar to this:

username:username123, 
password:password123, 

After load file to String you can do something like this:

int startPosition = file.indexOf("username") + 8; //+8 is length of username with colon
String username;
for(int i=startPosition; i<file.length(); i++) {
    if(file.charAt(i) != ',') {
        username += Character.toString(file.charAt(i));
    } else {
        break;
    } 

    System.out.println(username); //should prong username
} 

After edit all thing you want to edit, save edited string to file.

There are much ways to solve this issue. Read String docs to get to know operations on String. Without your code we cannot help you enough aptly.

1 Comment

My file is is not like that but thank you very much!
0

The algorithm is as follows:

  1. Open a temporary file to save edited copy.

  2. Read input file line by line.

  3. Check if the current line needs to be replaced
    Various methods of String class may be used to do this:

    • equals: Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
    • equalsIgnoreCase: Compares this String to another String, ignoring case considerations.
    • contains: Returns true if and only if this string contains the specified sequence of char values.
    • matches (String regex): Tells whether or not this string matches the given regular expression.
    • startsWith: Tests if this string starts with the specified prefix (case sensitive).
    • endsWith: Tests if this string starts with the specified prefix (case sensitive).

    There are other predicate functions: contentEquals, regionMatches

    If the required condition is true, provide replacement for currentLine:

   if (conditionMet) {
       currentLine = "Your replacement";
   }

Or use String methods replace/replaceFirst/replaceAll to replace the contents at once.

  1. Write the current line to the output file.
  2. Make sure the input and output files are closed when all lines are read from the input file.
  3. Replace the input file with the output file (if needed, for example, if no change occurred, there's no need to replace).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.