在IntelliJ调试/运行中将字符串缓冲区传递给java程序

如何在IntelliJ或Eclipse ….中完成在命令行上运行以下行的等价物:

java MyJava < SomeTextFile.txt 

我试图在IntelliJ中的Run / Debug Configuration的Program Arguments字段中提供该文件的位置

正如@Maba所说我们不能在eclipse / intellij中使用输入重定向操作符(任何重定向操作符),因为没有shell但你可以通过stdin模拟输入读取文件,如下所示

  InputStream stdin = null; try { stdin = System.in; //Give the file path FileInputStream stream = new FileInputStream("SomeTextFile.txt"); System.setIn(stream); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); stream.close() //Reset System instream in finally clause }finally{ System.setIn(stdin); } 

你不能直接在Intellij中这样做,但我正在开发一个允许将文件重定向到stdin的插件。 有关详细信息,请参阅我在此处对类似问题的回答[1]或尝试插件[2]。

[1] 在intellij中运行程序时模拟stdin的输入

[2] https://github.com/raymi/opcplugin

您可以使用BufferedReader来读取系统输入:

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } 
Interesting Posts