Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write to a specific line number in a txt file in Java

I'm currently writing my project for school in which requires me to read and write to txt files. I can read them correctly but I can only write to them at the end from an appended FileWriter. I would like to be able to overwrite things in my txt files on line numbers by first deleting the data on the line and then writing in the new data. I attempted to use this method...

public void overWriteFile(String dataType, String newData) throws IOException
{
    ReadFile file = new ReadFile(path);
    RandomAccessFile ra = new RandomAccessFile(path, "rw");
    int line = file.lineNumber(path, dataType);
    ra.seek(line);
    ra.writeUTF(dataType.toUpperCase() + ":" + newData);
}

but I believe that the seek method moves along in bytes rather than line numbers. Can anyone help. Thanks in advance :)

P.S. the file.lineNumber method returns the exact line that the old data was on so I already have the line number that needs to be written to.

EDIT: Soloution found! Thanks guys :) I'll post the soloution below if anyone is interested

public void overWriteFile(String dataType, String newData, Team team, int dataOrder) throws IOException
{
    try
    {
        ReadFile fileRead = new ReadFile(path);
        String data = "";
        if(path == "res/metadata.txt")
        {
            data = fileRead.getMetaData(dataType);
        }
        else if(path == "res/squads.txt")
        {
            data = fileRead.getSquadData(dataType, dataOrder);
        }
        else if(path == "res/users.txt")
        {
            data = fileRead.getUsernameData(dataType, dataOrder);
        }
        else if(path == ("res/playerdata/" + team.teamname + ".txt"))
        {
            //data = fileRead.getPlayerData(dataType, team.teamname, dataOrder);
        }
        BufferedReader file = new BufferedReader(new FileReader(path));
        String line;
        String input = "";
        while((line = file.readLine()) != null)
        {
            input += line + '\n';
        }
        input = input.replace(dataType.toUpperCase() + ":" + data, dataType.toUpperCase() + ":" + newData);
        FileOutputStream out = new FileOutputStream(path);
        out.write(input.getBytes());
    }
    catch(Exception e)
    {
        System.out.println("Error overwriting file: " + path);
        e.printStackTrace();
    }
}
like image 308
Elliot Lewis Avatar asked Sep 07 '14 21:09

Elliot Lewis


People also ask

How do you change one line in a text file in Java?

Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters. Instantiate the FileWriter class. Add the results of the replaceAll() method the FileWriter object using the append() method.

How do you write multiple lines in a text file in Java?

boolean append = true; String filename = "/path/to/file"; BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append)); // OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer. write(line1); writer. newLine(); writer.

How do you read a specific line from a text file in Java?

Java supports several file-reading features. One such utility is reading a specific line in a file. We can do this by simply providing the desired line number; the stream will read the text at that location. The Files class can be used to read the n t h nth nth line of a file.

How do you add text to a line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


2 Answers

A quick and dirty solution would be to use the Files.readAllLines and Files.write methods to read all lines, change the one you want to change, and overwrite the whole file:

List<String> lines = Files.readAllLines(file.toPath());
lines.set(line, dataType.toUpperCase() + ":" + newData);
Files.write(file.toPath(), lines); // You can add a charset and other options too

Of course, that's not a good idea if it's a very big file. See this answer for some ideas on how to copy the file line by line in that case.

Regardless of how you do it, though, if you are changing the byte length of the line, you will need to rewrite the whole file (AFAIK). RandomAcessFile allows you to move around the file and overwrite data, but not to insert new bytes or removes existing ones, so the length of the file (in bytes) will stay the same.

like image 100
Cyäegha Avatar answered Oct 20 '22 04:10

Cyäegha


Here is a link to a question just like this with a great answer: I want to open a text file and edit a specific line in java

Basically, you can't just edit that line, unless it'll be the exact same length.

Instead, you'll want to copy over every line, and then when you reach the line number of the line you want to change, instead of copying over the old line, just put in your new line.

The link I gave you has a great example on how to do this.

I hope this helps...if not, let me know, and I'll elaborate further on the post. Good luck :)

like image 20
Alex K Avatar answered Oct 20 '22 03:10

Alex K