1

I am creating a program to analyse a text file, I am using classes to do this with a run file. I am trying to get the results to print to a file. I have created a file called report.txt in the same folder however nothing prints in the file. I have done this using the full file path and it works fine however I want to do this with just the file name instead providing it is in the same folder.

Any help would be much appreciated on how to get the results to print to the file report.txt

My code is below:

Run file:

package cw;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;

public class TextAnalyser {
    //Declaration of all Scanners to be used in other classes.

    public static Scanner reader;
    public static Scanner Linesc;


    public static void main(String[] args) throws IOException {
        //User enters a file to be scanned.
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a filename");
        String filename = in.nextLine();
        File InputFile = new File(filename);

        //Assign all scanners to scan users file.
        Linesc = new Scanner(InputFile);


        LineCounter Lineobject = new LineCounter(); 


        Lineobject.TotalLines();

    }

}

Class file

package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;
public class LineCounter {
    public static void TotalLines() throws IOException {
                      Scanner sc = TextAnalyser.Linesc;
        PrintWriter out = new PrintWriter(new FileWriter("Report.txt", true));
        int linetotal = 0;
        while (sc.hasNextLine()) {
            sc.nextLine();
            linetotal++;
        }
         out.println("The total number of lines in the file = " + linetotal);

             out.flush();
            out.close();
         System.out.println("The total number of lines in the file = " + linetotal);
    }
}
TheHadimo
  • 147
  • 1
  • 1
  • 8

2 Answers2

0

If it works with a full file path but not with only the file name, it's probably because your current directory, where the file gets written, is not what you think it is. See Getting the Current Working Directory in Java to determine the current directory.

Community
  • 1
  • 1
JP Moresmau
  • 7,388
  • 17
  • 31
0
Scanner sc = TextAnalyser.Linesc;
PrintWriter out = new PrintWriter(new FileWriter(
        new File(LineCounter.class.getResource("Report.txt").toURI(), true));
int linetotal = 0;
while (sc.hasNextLine()) {
    sc.nextLine();
    linetotal++;
}

Replace the part of your code with the above, this should be able to find the report.txt file relative to the class folder.

ByteHamster
  • 4,884
  • 9
  • 38
  • 53