为什么c#控制台命令不能在java上运行
本文关键字:java 运行 不能 控制台 命令 为什么 | 更新日期: 2023-09-27 18:15:18
谁能告诉我为什么这个c#控制台命令不能在Java上运行?
我做了一个c#控制台程序,如下所示:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace face
{
class Program
{
public static void Main(string[] args)
{
String path = args[0];
byte[] imageBytes = File.ReadAllBytes(path);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
Bitmap S1 = new Bitmap(image);
Console.WriteLine(S1.GetPixel(2, 10));
}
}
}
当我运行Program.exe image.jpg
时,我得到:
然后我创建了一个简单的Java应用程序来运行Color [A=255, R=128, G=32, B=128]
Program.exe
可执行文件:
class project
{
public static void main(String[] args)
{
String comman="C:''WINXP''system32''Program.exe Sunset.jpg";
try
{
Process process = Runtime.getRuntime().exec(comman);
System.out.println(process.getOutputStream());
} catch (Exception e)
{e.printStackTrace(System.err);}
}
}
当我尝试运行Java应用程序时,得到以下错误:
Program.exe遇到问题,需要关闭。给您带来的不便,我们深表歉意。
您可能想要更改
String comman = "C:''WINXP''system32''Program.exe Sunset.jpg";
String[] comman = { "C:''WINXP''system32''Program.exe", "Sunset.jpg" };
正如评论所说,这可能是因为c#程序无法打开文件:您应该为它指定一个绝对路径,因为在这种情况下,让实际的工作目录正常工作可能是不必要的痛苦。此外,在c#程序中捕捉异常(例如"无参数"answers"文件未找到"的情况)也不会有什么坏处。
c#进程是java进程的子进程,并在java VM终止时自动终止。因为流程是异步启动的,所以这将立即发生。如果您对输出感兴趣,请替换
System.out.println(process.getOutputStream());
with(例如)
InputStream inputStream = process.getInputStream();
int c;
while ((c = inputStream.read()) >= 0) {
System.out.print((char) c);
}
如果没有,写
process.getInputStream().close();
process.waitFor();
除了别人说的,我不认为System.out.println(process.getOutputStream());
会输出你想要的东西-即执行的c#可执行文件的输出。
System.out.println()
对Process.getOutputStream()
的返回类型OutputStream
没有过载。因此将选择System.out.println(Object)
重载,它将调用OutputStream.ToString()
,它不是c#程序的输出,而是(很可能,在这里请原谅我)输出流实例的完全限定类型名。
查看以下问题/答案,例如,了解更多信息
您需要检查您提供的exe和映像文件的路径。当我检查这段代码并执行它时,我得到以下输出java.io.BufferedOutputStream@c17164
我给你修改后的代码
public class Test
{
public static void main(String[] args)
{
String path="C:''C#Sample''ImageDisplayDemo''ImageDisplayDemo''bin''Debug''ImageDisplayDemo.exe E:''Users''Public''Pictures''Sample Pictures''Desert.jpg";
try
{
Process proc=Runtime.getRuntime().exec(path);
System.out.println(proc.getOutputStream());
}
catch(Exception ex)
{
}
}
}