0

I've trying to choose a specific line from file and I sort of got it, but I can't think of a way to change Strings or ints in console. For example there is a name and age: Tom 19 Jennifer 22

I choose line number 1 and I want to change something like, making Tom older, but i just can't figure it out, please help. Sorry for waisting your time if it's easy. Thank you.

    FileReader fr = null;
    LineNumberReader lnr = null;
    String str;
    int i;
    int currLine = 1;

    System.out.print("Which line to print?:  ");
    Scanner scan = new Scanner(System.in);

    int d = scan.nextInt();

    // create new reader
    fr = new FileReader("test.txt");
    lnr = new LineNumberReader(fr);

    // read lines till the end of the stream
    while ((str = lnr.readLine()) != null) {
        if (currLine == d) { // if current line number is 4, print

            // prints string
            System.out.println(str);
        }

        currLine++;
    }

    // closes the stream and releases system resources
    if (fr != null)
        fr.close();
    if (lnr != null)
        lnr.close();
}
dziugas009
  • 49
  • 5

2 Answers2

0

Basically what i think you want is read a file and write a new file with the new modifications. Basically what you would need to do is readLine from test.txt and write the same line in testNew.txt. When you detect the line you want to change you write over what you receive from test.txt to testnew.txt. In later ways you can do things like change test.txt to test.old.txt and create a new test.txt and in the end delete test.old.txt or something so that you do not need to have a new file.

Rafael Saraiva
  • 908
  • 2
  • 11
  • 23
0

Inside your while loop, use a filewriter to modify the content by searching and replacing the string or int.

Try implementing the code provided in this link. It can help you to complete what you are looking for

Community
  • 1
  • 1
BDRSuite
  • 1,594
  • 1
  • 10
  • 15