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?
-
1Can you share the code that you tried??sn-– sn-2020-11-01 08:22:43 +00:00Commented 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.Alan K– Alan K2020-11-01 08:25:05 +00:00Commented Nov 1, 2020 at 8:25
4 Answers
In general you can do it in 3 steps:
- Read file and store it in String
- Change the String as you need (your "username,password..." modification)
- 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();
}
});
}
}
Comments
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
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
The algorithm is as follows:
Open a temporary file to save edited copy.
Read input file line by line.
Check if the current line needs to be replaced
Various methods ofStringclass 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,regionMatchesIf 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.
- Write the current line to the output file.
- Make sure the input and output files are closed when all lines are read from the input file.
- Replace the input file with the output file (if needed, for example, if no change occurred, there's no need to replace).