update midle values of the text file...
hello all
I can write to a NEW text file "myfile.txt" by using:
BufferedWriter out = new BufferedWriter(new FileWriter("myfile.txt"));
out.write(databaseName +"\n");
out.write(hostName +"\n");
out.write(portName +"\n");
out.write(userName +"\n");
out.write(pass +"\n");
...
out.write(value1 +"\n");
out.write(value2 +"\n");
...
Now supose that the file "myfile.txt" is already exited and I only want to write to midle of the file (e.g I want to update the value1-line 6 and value2 - line 7 and want to keep other values in the file)
How I can do that...
Many thanks
shuhu
[668 byte] By [
suhua] at [2007-11-27 6:11:17]

You can't write to a file that isn't open, and you can't insert text into the middle of the file without writing over anything... what you have to do is open the file, read to where you want to write, then write your line, and then write out the rest of the file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class ReplaceMe {
public static int PERSISTENT = 1;
public static void main(String[] args) {
System.out.println("PERSISTENT = " + PERSISTENT);
try {
BufferedReader br = new BufferedReader(
new FileReader("ReplaceMe.java") );
ArrayList<String> tehCodez = new ArrayList<String>();
String line;
while ( (line = br.readLine()) != null) {
if ( line.contains("int PERSISTENT = ") &&
line.contains("static") ) {
tehCodez.add("public static " +
"int PERSISTENT = " + (PERSISTENT+1) + "; // Found it.");
} else {
tehCodez.add(line);
}
}
br.close();
BufferedWriter bw = new BufferedWriter(
new FileWriter("ReplaceMe.java") );
for (String aLine: tehCodez) {
bw.write(aLine);
bw.newLine();
}
bw.close();
Runtime.getRuntime().exec("javac ReplaceMe.java");
} catch(Exception e) {
e.printStackTrace();
}
}
}
Thanks all
In my solution, i have to use three separated files: one for some first data, one for middle data and one for ....some last data....
So I donot have to rewrite whole data if there is only one file.
And this is not good solution
Message was edited by:
suhu
suhua at 2007-7-12 17:17:29 >

Given the data you posted, I'd suggest moving from a fixed-line-position notation to something richer, like java.util.Properties files, or XML, or an actual relational database. Properties files are probably easiest.