Reputation: 31041
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?
Upvotes: 11
Views: 33242
Reputation: 1
public void main() throws IOException {
String newString = "The New String";
File myFile = new File("PathToFile");
// An array to store each line in the file
ArrayList<String> fileContent = new ArrayList<String>();
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
// Reads the file content into an array
fileContent.add(myReader.nextLine());
}
myReader.close();
// Removes Original Line
fileContent.remove(0);
// Enters New Line
fileContent.add(0, newString);
// Writes the new content to file
FileWriter myWriter = new FileWriter("PathToFile");
for (String eachLine : fileContent) {
myWriter.write(eachLine + "\n");
}
myWriter.close();
}
Upvotes: 0
Reputation: 6711
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..
Upvotes: 16
Reputation: 59346
If the new line has a different amount of characters (bytes) than the original first line, you will have to re-write the whole file to get rid of the gap or avoid overwriting part of the second line.
Of course, various tools like String.replaceFirst(String regex, String replacement)
(javadoc) or the RandomAccessFile
(javadoc) can help you with this task.
Upvotes: 4
Reputation: 13867
apply a regex only once. String.replaceFirst("regex", "replacementstring") : http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
Open the file as RandomAccessFile. Read the 1st line into a string and then apply the change and then write the string back.
Upvotes: 1
Reputation: 138874
You want a RandomAccesssFile. Using the file you can read and write wherever you want in the file.
It is much like an InputStream and OutputStream, but it allows reading and writing wherever you like.
Upvotes: 3