Can I use Scanner class in text file for getting information?
-
21-08-2019 - |
Question
this code is correct??
String note = "text.txt";
FileWriter file = new FileWriter(note);
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name:");
String name = sc.next();
file.close();
How can I pass this file to the program as a command line argument???
Solution
Well, personally I'd never use FileWriter
as it uses the system default encoding, which is a nasty thing to do most of the time. I prefer FileOutputStream
+ OutputStreamWriter
. However, having said that...
What do you want to pass as the command line argument? The file name? That's easy:
public static void main(String[] args)
{
// Insert error checking here (e.g. args.length == 0)
String note = args[0]; // For the first argument
// Rest of code here
}
If that's not what you mean, please edit your question to clarify it.
Judging by the title, you may be wanting to load from a file instead of from System.in
. In that case, you just need to pass in a File
object, or an InputStream
(such as FileInputStream
) or indeed a Readable
(such as InputStreamReader
). If you're going to pass in a File
or InputStream
, I'd strongly recommend that you pass in the character encoding name as well. (Quite why it takes it as a string instead of a Charset
is beyond me, but the Java API is basically pretty bad when it comes to encodings.)