I need to use PrintWriter in Java to read a document saved on the computer and print it into an array. We must use a skeleton and develop our code from that. I think I understand the concept, except the compiler keeps telling me the file does not exist. I think the problem may be that I have an iMac and it does not have c drive, at least not labeled that way. What am I doing wrong? I included the code in my code so far...
import java.io.PrintWriter;
import java.io.File;
import java.util.*;
import java.text.*;
public class pWriter{
public static void main(String[]args) throws Exception{
Scanner stdln = new Scanner(new File("c://FileName.txt));
String[] line = new String[238];
while (stdln.hasNextLine()){
int i = 0;
line[i] = stdln.nextLine();
i++;
}
}
}
PrintWriter
is for output. Scanner
can be used for input. And you aren't closing your String literal,
// "c:/FileName.txt" // <-- one slash and a quote at the end.
File f = new File(System.getProperty("user.home"), "fileName.txt");
For fileName.txt
in your home folder.
I think you meant to declare i
outside the loop, you could also use a try-with-resources
like
File f = new File(System.getProperty("user.home"), "fileName.txt");
try (Scanner stdln = new Scanner(f)) {
String[] line = new String[238];
int i = 0; // <-- outside the loop.
while (stdln.hasNextLine()){
line[i] = stdln.nextLine();
i++;
}
} catch (Exception e) {
e.printStackTrace();
}