I am trying to read a file using a string input as the filename. For example, if the filename is datafile.txt then if the input is "datafile.txt" and there is a file of that name in the directory, how do I read it? Here is my initial code:

Scanner kbd = new Scanner(System.in);
String file = kbd.next();

then I have code further down as follows:

Caesar myCaesar = new Caesar(file);

However, it doesn't like the Caesar(file) because file is a string. Any help is much appreciated.

Recommended Answers

All 2 Replies

Uhm, wrap "file" in New File(file)? If your "Caesar" constructor needs a file as an argument.

As OP said, you can just make a new File with the constructor public File(String filename). Besides that, a file can generally read in 2 ways, using a scanner, or by using a bufferedreader. Both have their uses, though generally it doesn't matter. I suggest you look up both classes, do a google search, and tell us how it went.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.