views:

272

answers:

1

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???

+2  A: 

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.)

Jon Skeet
for using command line you assigned args[0] to the name of the file.this is just the way that we can pass the path of our file with the command line to the application.can you give me the other source except from the one that is in java tutorials???
Johanna
Pretty much any Java book will tell you about this. The "main" method receives the command line parameters as a String array parameter - it's as simple as that.
Jon Skeet