savage24x
savage24x

Reputation: 23

Read line from text file Java?

So I'm new to Java, and everything I'm trying, isn't working. There are so many different ways to read from a file, so I'm wondering the easiest way. Basically, it's a Mad Libs application. One method. I have been trying to run this successfully, and I get an error on the file.close() function. If I take it away, I get FileNotFoundException errors. So I'm kind of lost. What should I change?

public static void main(String[] args) throws Exception {
    String[] nouns = new String[4];
    String[] verbs = new String[6];
    String[] adjectives = new String[7];
    Scanner s = new Scanner(System.in);
    System.out.println("Please input 4 nouns, press \"Enter\" after each input.");
    for(int i=0; i<4; i++){
        nouns[i] = s.next();
    }
    System.out.println("Please input 6 verbs, press \"Enter\" after each input.");
    for(int i=0; i<6; i++){
        verbs[i] = s.next();
    }
    System.out.println("Please input 7 adjectives, press \"Enter\" after each input.");
    for(int i=0; i<7; i++){
        adjectives[i] = s.next();
    }
    File file = null;
    FileReader fr = null;
    LineNumberReader lnr = null;

    try {
        file = new File("H:\\10GraceK\\AP Computer Science\\Classwork\\src\\madlib.txt");
        fr = new FileReader(file);           
        lnr = new LineNumberReader(fr);
        String line = "";           
        while ((line = lnr.readLine()) != null) {
            System.out.println(line);               
        }
    } finally {
        if (fr != null) {
            fr.close();
        }
        if (lnr != null) {
            lnr.close();
        }
    }
}

Ok, I fixed the exception. Now the text in the file reads verbs[0], and stuff like that, but it actually outputs the verbs[0], not the word in the array. How do I append a string in the array to the string that was read?

Upvotes: 2

Views: 6127

Answers (3)

Reimeus
Reimeus

Reputation: 159864

The method close is undefined for File. Use FileReader.close instead. Replace

file.close();

with

fr.close();

In fact closing the LineNumberReader will suffice as this will close the underlying FileReader. You can place the close in a finally block. See this example

Upvotes: 6

Marcus Becker
Marcus Becker

Reputation: 352

The Scanner API improved and turn it more easy:

try {
    Scanner sc = new Scanner(new File("text.txt"));
    sc.useDelimiter(System.getProperty("line.separator"));
    String ln = sc.next();

} catch (FileNotFoundException ex) {
    Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}

Upvotes: 0

Peter Svensson
Peter Svensson

Reputation: 6173

As always I have to recommend commons-io when it comes to reading files and streams.

Try using for example:

IOUtils.readLines

The error in your code is as @Reimeus mentioned the missing method.

Upvotes: 2

Related Questions