java 中 .cmd文件,如何使用Java在cmd窗口中显示.txt文件的内容?

I am working on a project and I want to display the contents of a .txt file on the CMD window. I wrote this piece of code to open a demo.txt file on cmd but it does not work. The "path" variable contains the location where the demo.txt file is placed (as you can see obviously).

public static void main(String[] args){

try{

String path = "C:\\Users\\Hp\\Documents\\NetBeansProject\\Project\\build\\classes\\";

//cmd command to open open the txt file on cmd window

String command = ("type " + path + "\\demo.txt");

//executing this command on cmd using java

Process process = Runtime.getRuntime().exec(command);

}catch(IOException e){

e.printStackTrace();

}

This code produces the following output:

hbSKp.png

Don't mind the cringey or faulty code as I'm still a beginner in Java programming.

解决方案

The executable that displays a CMD window (as you refer to it in your question) is:

C:\Windows\System32\conhost.exe

Use class java.lang.ProcessBuilder to launch conhost.exe

ProcessBuilder pb = new ProcessBuilder("conhost.exe");

Process proc = pb.start();

When you run this java code a CMD window will be displayed.

Note that you can't type commands into this window because its standard input is your java program and not the keyboard. However you can send commands to the window from your java code. You simply write to the output stream of the Process instance.

First get the output stream of the Process

OutputStream os = proc.getOutputStream();

Then write your desired commands to the output stream.

I used the [Windows] start command to open a separate window – which you can interact with – and ran your desired command in that window. And finally, I closed the window that I opened via conhost.exe. As a result, the window opened by the start command remains open and the java program terminates.

Here is the entire code.

import java.io.IOException;

import java.io.OutputStream;

public class Script {

public static void main(String[] args) throws IOException, InterruptedException {

ProcessBuilder pb = new ProcessBuilder("conhost.exe");

Process proc = pb.start(); // throws java.io.IOException

OutputStream os = proc.getOutputStream();

os.write("start /D C:\\Users\\Hp\\Documents\\NetBeansProject\\Project\\build\\classes type demo.txt".getBytes()); // throws java.io.IOException

os.write(System.lineSeparator().getBytes()); // throws java.io.IOException

os.write("exit".getBytes()); // throws java.io.IOException

os.write(System.lineSeparator().getBytes()); // throws java.io.IOException

os.flush(); // throws java.io.IOException

int status = proc.waitFor(); // throws java.lang.InterruptedException

System.out.println("Exit status = " + status);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值