class - Printing to file using PrintWriter in Java not working with filename -
i creating program analyse text file, using classes run file. trying results print file. have created file called report.txt in same folder nothing prints in file. have done using full file path , works fine want file name instead providing in same folder.
any appreciated on how results print file report.txt
my code 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 scanners used in other classes. public static scanner reader; public static scanner linesc; public static void main(string[] args) throws ioexception { //user enters file scanned. scanner in = new scanner(system.in); system.out.println("enter filename"); string filename = in.nextline(); file inputfile = new file(filename); //assign scanners 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 file = " + linetotal); out.flush(); out.close(); system.out.println("the total number of lines in file = " + linetotal); } }
if works full file path not file name, it's because current directory, file gets written, not think is. see getting current working directory in java determine current directory.
Comments
Post a Comment