简体   繁体   中英

File not writing when java program is executed from command line

I have this code which executes perfectly from an IDE, making a new file and writing to it, but when I run it from command-line it won't write to a file. It still prints the println and receives my scanner input, but it won't write a new file.

public class test {
   public static void main(String[] args){
      Scanner s = new Scanner(System.in);
      File f = new File("print.txt");
      System.out.println("'y' for yes or 'n' for no");

      try {
         BufferedWriter k = new BufferedWriter(new FileWriter(f));
         if (s.next().equals("y")) {
            k.write("y");
         } 
         else {
            k.write("n");
         }
         k.flush();
      }
      catch (Exception e){
         e.printStackTrace();
      }
   }
}

I am on Windows 10 and the commands I'm using to execute the program are

javac "C:\Users\David\Documents\Java\test.java"
java -cp "C:\Users\David\Documents\Java" test

Thank you for any help.

Nevermind, I realized that the file was just being created in a different directory since I didn't specify a directory to write the file to in the code. Silly me.

yeah.. you got it. While using cp- (ClassPath cmd) you must specify the name of directory where that java file needs to get saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM