Writing to a specific line in a text file
Hi, I have a problem where I only want to replace one line in a text file, while keeping all the others the same. For example, my text file looks something like this:
0
3
10
18
7
4
2
And, in the actual program, I do something like this:
-Read line 3, set it to string x
-Change the value of string x
And now I want to replace line 3 with x, but I have no idea how to.
Re: Writing to a specific line in a text file
There are two ways:
1. Write to a temporary file sequentially, only writing out new data when you need to.
2. Use the RandomAccessFile class. See: Java Tips - How to use Random Access file and RandomAccessFile (Java 2 Platform SE v1.4.2)
Re: Writing to a specific line in a text file
Quote:
Originally Posted by
The_Mexican
Hi, I have a problem where I only want to replace one line in a text file, while keeping all the others the same. For example, my text file looks something like this:
0
3
10
18
7
4
2
And, in the actual program, I do something like this:
-Read line 3, set it to string x
-Change the value of string x
And now I want to replace line 3 with x, but I have no idea how to.
here's an example
Code :
public class ReadWriteFile {
public static void main(String[] args) throws FileNotFoundException, IOException{
Formatter output = new Formatter(args[1]);
Scanner sc = new Scanner ( new File(args[0]) );
....
String replace = "x";
while (sc.hasNext() ){
String line = sc.nextLine();
.....
if ( couter==3 ){
line = replace;
}
output.format("%s\n", line );
}
output.close();
}
}