简体   繁体   English

从命令行执行Java程序时文件未写入

[英]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. 我有这段代码可以从IDE完美执行,生成一个新文件并写入其中,但是当我从命令行运行它时,它不会写入文件。 It still prints the println and receives my scanner input, but it won't write a new file. 它仍会打印println并接收我的扫描仪输入,但不会写入新文件。

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 我在Windows 10上,用于执行程序的命令是

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. 使用cp-(ClassPath cmd)时,必须指定需要保存该Java文件的目录名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java在命令行提示符下不断更新一行时从命令行执行的程序获取输出 - Java getting output from program executed in command line when it constantly updates a single line in the command prompt 不同的输出-在命令行中运行mathtext时以及使用apache-commons-exec从Java程序执行命令时 - Different output — when running mathtext in command line and when the command is executed from a java program using apache-commons-exec Java文件从命令行执行,但不是从浏览器(Apache)执行? - java file executed from command line but not from browser(apache)? 通过命令行jdb运行Java程序可以正确执行,但作为Java命令行执行时会失败 - Running java program through command-line jdb executes correctly but fails when executed as java command-line Java文件在命令行中执行但在浏览器中不执行 - Java file executed in command line but not in browser 如何在由命令行执行的Java程序中包含JAR文件(Windows) - How to include JAR file in a java program that is being executed by command line (Windows) 从依赖于 jar 文件的命令行运行 Java 程序? - Running a Java program from the command line that depends on a jar file? 从Linux命令行运行Java程序需要一个附加文件 - Running Java program from Linux command line that requires an additional file 使用Java将命令行输出写入文件 - Writing command line output to a file with in Java 从命令行运行Java程序时无法加载资源 - Failing to load resource when running java program from command line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM