Search code examples
javacommand-linefilewriterbufferedwriter

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.


Solution

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