前言
最近在开发关于使用Java Process时,发现我的输出流总是写入不到我的InputStream里面,怎么写都没反应,后来经过仔细排查和严格筛查,原来解决方案那么办法那么简单!
解决思路
由于我是通过Process启动Java Server Core 所以在cmd窗体时,正常都需要写入完命令之后回车!
由于转到代码里,我总认为例如 BufferedOutPutStream 缓冲输出流是会write后自动下一行继续写入,后面发现只是单行write,需要手动换行
案例代码
Runnable
/**
* 服务器控制台运行线程
*
* @author admin
* @date 2022/07/12
*/
@Data
public class ServerConsoleRunnable extends TimerTask {
private ServerProcess process;
private JTextArea textArea;
/**
* 服务器控制台可运行
*/
public ServerConsoleRunnable(){
}
/**
* 服务器控制台可运行
*
* @param process 过程
* @param textArea 文本区域
*/
public ServerConsoleRunnable(ServerProcess process, JTextArea textArea){
this.process = process;
this.textArea = textArea;
}
@Override
public void run() {
try{
if(process.getProcess() == null){
return;
}
if(process.getProcess().getInputStream() != null){
InputStream inputStream = process.getProcess().getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int len = 0;
byte[] str = new byte[bufferedInputStream.available()];
while((len = bufferedInputStream.read(str)) != -1){
String text = new String(str);
textArea.append(text);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
OutPutStream
/**
* 停止服务器
*/
public void stopServer(){
try {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(process.getOutputStream());
bufferedOutputStream.write("stop".getBytes(StandardCharsets.UTF_8));
bufferedOutputStream.write("\n".getBytes(StandardCharsets.UTF_8));
bufferedOutputStream.flush();
bufferedOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
结束语
Java踩坑笔记 —— 关于OutPutStream流无法在Process应用场景写入失败解决方案
- 如果对你有帮助的话可以给我点赞收藏,十分感谢
- 致力做优、好、细、精学习笔记分享给大家
- 可以转载 需标明 出处 本文链接。
- 笔者一个开源项目:我的世界开服助手 希望大家可以点一下star哦
感谢你的观看。