2

I'm stuck on writing to a specific line using File, BufferedReader, & BufferedWriter.

What I'm trying to achieve is getting my text files total line count (-3) & writing to that line.

Currently it just erases the whole file & nothing is written.

Image of what I'm doing:

enter image description here

(In Image) line 25 is blank & 26 doesn't contain a doc. it contains "}"

& My code:

    package com.tests.writer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFrame;

public class NewWriter {

    static Integer tableCount;

    static File file;
    static FileWriter fw;
    static FileReader fr;
    static BufferedWriter bw;
    static BufferedReader br;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test {New Writer}");
        frame.setBounds(500, 500, 500, 500);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setAutoRequestFocus(true);
        try {
            startApplication();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void startApplication () throws IOException {
        writeToFile ();
    }

    private static void writeToFile () throws IOException {
        Integer lineTCount = 0;
        file = new File("Tables.txt");
        if (file.exists()) {
            fw = new FileWriter(file.getAbsolutePath(), true);
            fr = new FileReader(file.getAbsolutePath());
            bw = new BufferedWriter(fw);
            br = new BufferedReader(fr);

            for (String line = br.readLine(); line != null; line = br.readLine()) {
                lineTCount++;
                System.out.println(lineTCount);
              }
            System.out.println(lineTCount);
            bw.write("Test Text to insert");
            System.out.println("done");
            System.exit(0);
        } else {
            file.createNewFile();
            System.out.println("New File = " + file.toString());
            writeToFile();
        }
    }

}

If there is an easier way of doing this, I'm open to all idea's as I'm still not familiar with Java.io

& If anyone can tell me this is correct. I may have to add the whole file to a list, add the new text then re-write the file.

Ryan
  • 83
  • 2
  • 9

2 Answers2

1

The bw pointer does not move when you loop through your file. Use this to write to a specific location in your file. Also why are there two variables lineCount & lineTCount

public void write(String s,
         int off,
         int len)
           throws IOException

Ref: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#write(java.lang.String,%20int,%20int)

EDIT: you are right, my bad. You will have to read the previous contents -> make the changes that you want and rewrite the whole file again.

Aakash
  • 1,860
  • 19
  • 30
  • write(str, int, int) is used for printing a portion of your string. I'm trying to print a string to a specific line in this case (lineTCount - 3) which atm in the file is line 25. I've updated the code & gotten rid of the other unneeded Integer. – Ryan Sep 30 '14 at 05:21
1

There are a few things you did a little bit off. First and foremost; the reason your file is returning empty is because you aren't calling

bw.close();

After you have finished writing to the file.

I don't know of any way to write to a specific part of a file. I don't think there is one.

What you'll have to do is re-write the file. Basically, make a temporary copy, then write all the lines just as before, except for the third-to-last one.

See this question: I want to open a text file and edit a specific line in java

(I don't know how to mark questions as duplicate)


BufferedWriter's 'write(String s, int off, int len)' method actually states

Writes a portion of a String.

Note; that is NOT 'writes to a specific location in the file'.


EDIT

I wouldn't use System.exit(0);. That tells your OS 'This execution failed'. You should just let your program close itself normally by excluding this line. See: When to use system.exit(0)?

Community
  • 1
  • 1
Multihunter
  • 5,520
  • 2
  • 25
  • 38