Colaflaske
Colaflaske

Reputation: 23

Java issue: Handling an argument as a file and reading it

So I'm trying to figure this one out. I have a file, let's say it's text.txt. I want to open this using "Open with.." in Windows. From what I've figured out, this Windows function is just passing the file path as an argument to the program. In Java, I have this at the moment:

import java.io.*;
public class program {


public static void main(String[] args) throws IOException {
       File inFile = new File(args[0]);

    InputStreamReader fileIO = new InputStreamReader(inFile);
    fileIO.toString();
    System.out.println(fileIO);
    fileIO.close();
}

}

When I run it, I get this.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The constructor InputStreamReader(File) is undefined
    at program.main(program.java:8)

I have put the file path in the run configuration and not even my Google Fu is working on this one. I'm quite tired tho, so I'll just leave this here for now.

EDIT: Apparently the superclass is java.lang.*, but whatever, that shouldn't matter(?)

Upvotes: 0

Views: 70

Answers (2)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29176

InputStreamReader has no constructor which takes a File object as an argument.

Use the following code instead -

InputStreamReader fileIO = new InputStreamReader(new FileInputStream(inFile));

Read the documentation here.

If you don't mind Apache Commons library, then there is a more simpler way to do this -

File inFile = new File(args[0]);
String content = FileUtils.readFileToString(inFile);
System.out.println(content);

Upvotes: 0

René Link
René Link

Reputation: 51463

Use a FileInputStream

InputStreamReader fileIO = new InputStreamReader(new FileInputStream(inFile));

because InputStreamReader does not have a constructor that takes a file argument.

Upvotes: 1

Related Questions