Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is FileReader not a class in NetBeans?

So I just switched to NetBeans today because my eclipse had been crashing for a bizillion times. However when I am learning something on reading files, I can't seem to import the class for FileReader.

When I try to import something for FileReader, it just asks me if I want to create method FileReader(java.io.File). Is this just a difference between Eclipse and Netbeans?

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;



File file1 = new File("test.txt");

try(BufferedReader bf1 = new BufferedReader(FileReader(file1))){


}catch (IOException ex) {
       System.out.println("haha");
}
like image 217
whales Avatar asked Mar 14 '23 21:03

whales


2 Answers

You simply haven't imported it - you either need a wildcard import:

import java.io.*;

or the specific import:

import java.io.FileReader;

As noted by Titus, you're also missing a new before you use FileReader. This:

try(BufferedReader bf1 = new BufferedReader(FileReader(file1))){

should be:

try(BufferedReader bf1 = new BufferedReader(new FileReader(file1))){

Now it's possible that you're used to Eclipse importing things automatically for you more than Netbeans - looking in common packages (or even all packages) for the type that you mention, and offering to import it for you. I don't know about the Netbeans functionality here, but it wouldn't surprise me if it's a little different.

I'd also encourage you to avoid FileReader anyway - it doesn't let you specify the encoding used to read the file. As of Java 7 there's a more convenient method in java.nio.Files anyway:

try (BufferedReader reader = Files.newBufferedReader(file1.toPath())) {
    ...
}

Or start off with a Path:

Path file1 = Paths.of("test.txt");
try (BufferedReader reader = Files.newBufferedReader(path)) {
    ...
}

This will use UTF-8 by default, or you can specify an encoding if you wish.

like image 74
Jon Skeet Avatar answered Mar 20 '23 07:03

Jon Skeet


You're missing two things here. First, you must import the class:

import java.io.FileReader;

Second, FileReader is a class, not a method - you're missing the new operator:

try (BufferedReader bf1 = new BufferedReader(new FileReader(file1))) {
    // Here ---------------------------------^
    // etc...
like image 27
Mureinik Avatar answered Mar 20 '23 06:03

Mureinik