0

To clarify my question, I am writing to a text file located on my computer which has text content already in it. The code below writes to the text file without erasing any of its contents but now I want to specify what line it writes to. Currently it has an if statement to catch if the word 'Done' exists within in the line, it is recognized since it does write to the file. My problem is trying to get it to write to the line that says 'Done'. It writes to the very bottom, last line of code. How can I fix this?

The method readNumLines is the number of lines contained within the file. Reading is the text file name.

int i = 0;
    BufferedReader reader = new BufferedReader(new FileReader(path+reading));
    BufferedWriter writer = new BufferedWriter(new FileWriter(path+reading, true));
    String line = null;
    while ((line = reader.readLine()) != null && i < readNumLines(reading)-1) {
        if(line.contains("Done")){
            writer.write("\nCHECK!\n");
            writer.close();
        }
        i++;
    }
miken32
  • 42,008
  • 16
  • 111
  • 154
Abszol
  • 57
  • 3
  • 11

3 Answers3

1

I suggest reading the whole file into a variable (string, array or list). You can easily modify specific lines then and write everything back to the file.

1) Reading File into an array: Store text file content line by line into array

2) Manipulate array:

for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (line.contains("Done")) {
                lines[i] = line + "\nCHECK!\n";
                break;
            }
}

3) Write string array to file: Writing a string array to file using Java - separate lines

The problem also can be related to this line:

writer.write("\nCHECK!\n");

the first "\n" forces the "CHECK" to be written in a new line. This assumes that your "Done" line is the last line and does not end with "\n".

Community
  • 1
  • 1
Alex
  • 58
  • 4
  • I thought of this before but was hoping there would be an easier way to do so. – Abszol Oct 23 '14 at 20:21
  • If your file is really really big you might have to use another solution since you can not load it completely. But this solution will probably not be easier. – Alex Oct 23 '14 at 20:24
0

This is my way of doing it.The idea is simple write everything including the new line to a temp file and then rename the temp file to the Original file and delete the orginal one. NOTE: I pulled this code staigt from one of my project and therefore I may have forgotten to change something. So if it doesn't work let me know and I will have a look. Hope this helps :)

            String line;//You need to specify those
            File infile;

            // temp file
            File outFile = new File("$$$$$$$$.tmp");

            // input
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(inFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));

            // output         
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            PrintWriter out = new PrintWriter(fos);
            String thisLine = "";
            int i =1;
            try {
                while ((thisLine = in.readLine()) != null) {
                   if(in.contains("Done"))//the check for done 
                       out.println(line);                  
                   }
                   out.println(thisLine);
                   i++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.flush();
            out.close();
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inFile.delete();
            outFile.renameTo(inFile);
Roan
  • 1,200
  • 2
  • 19
  • 32
  • This actually didn't work, I'm running this on Linux and it seems that renameTo isnt' in my favor right now. – Abszol Oct 23 '14 at 21:48
  • Weird but I don't really know how linux works so if it is something with linux I don't know, sorry. Where there any errors? – Roan Oct 23 '14 at 21:51
  • Oddly no, it just didn't even rename the file at all and I read into it. People are stating that its heavily platform oriented. – Abszol Oct 23 '14 at 22:18
  • So evereything is written correctly to the file it is just not correctly renamed? Because in that case you might be able to find a way that renames the file correctly. – Roan Oct 23 '14 at 22:20
  • I'm going to keep looking around, someone said try file.move so I can place the file somewhere on my system then move it to the location it needs to be at. – Abszol Oct 23 '14 at 23:45
  • Yeah sure just try everything you can come up with if I think of something I will let you know too. – Roan Oct 24 '14 at 06:22
0

When using Java 8, you might try this:

final Path myFile = Paths.get("path\\to\\yourFile.txt");
final int lineNumWhereToInsert = 2;
final String stringToInsert = "insertion test";

try {
    final List<String> lines = Files.lines(myFile).collect(Collectors.toList());
    lines.add(Math.min(lineNumWhereToInsert, lines.size()), stringToInsert);

    try (final BufferedWriter out = Files.newBufferedWriter(myFile, Charset.forName("UTF-8"))) {
        for (final String line : lines) {
            out.append(line).append(System.lineSeparator());
        }
    }
} catch (IOException) {
    ex.printStrackTrace();
}
ifloop
  • 8,079
  • 2
  • 26
  • 35