I started learning java relatively recently as my first computer language independently and would like to see if my approach is efficient. An exercise in the book I am studying from tells me to read a file and write it into a seperate file with each line numbered.
Here is my solution
public class FileStuff
{
public static void main (String [] args)
{
System.out.println("Which file do you want to read");
Scanner in = new Scanner(System.in);
String fileInput = in.next();
System.out.println("Which file do you want to write to?");
String fileOutput = in.next();
Scanner goThrough = null;
PrintWriter print = null;
String content ="";
try
{
print = new PrintWriter(fileOutput);
goThrough = new Scanner(new File(fileInput));
while(goThrough.hasNextLine())
{
content = goThrough.nextLine();
writeToLine(content, print);
}
} catch(FileNotFoundException e)
{
e.getMessage();
}finally
{
goThrough.close();
print.close();
}
}
static int lineNumber = 1;
static void writeToLine(String line, PrintWriter out) throws FileNotFoundException
{
try
{
out.println(String.format("/* %d */ %s ",lineNumber,line));
lineNumber+=1;
}
catch(Exception e)
{
e.getMessage();
}
}
}
Concerns
I have several inquiries about my code as I cannot understand my book clearly, and coding practicing questions.
Firstly, is it ok to initialize goThrough
and print
outside the try
block as null? I did this because I wanted to close the Scanner
and PrintWriter
inside the finally block, but did not want to define something inside the try block since it is a different scope from the finally
block
Secondly: Is it fine to throw FileNotFoundException
at my method writeToLine
? Or should I be throwing it after public static void main(String [] args)
, I have seen it done both ways in my book.