简体   繁体   中英

PrintWriter in Java, Can't find file error

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();
}

First you need to find the real path to your input file. For example, if it is in your home directory, it could be: "/Users/yourusername/FileName.txt"

Then you need to fix your while loop from this:

while (stdln.hasNextLine()){
    int i = 0;
    line[i] = stdln.nextLine();
    i++;
}

to this:

int i = 0;
while (stdln.hasNextLine()){
    line[i] = stdln.nextLine();
    i++;
}

Then you need to print your array of lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM