论坛首页 Java版

JAVA调用linux命令出现的问题

浏览 453 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
时间:2008-03-07 关键字: java调用linux命令出现的问题
HI,
在开发过程中遇到这样一个问题,使用java调用linux系统命令出现下面现象:
javac A.java
段错误

上网查了,说是和jdk有关,但是换过之后(从1.5换到了1.4)仍出现该错误

同时,在solaris10下是可以编译并执行(但要求os 是 linux)

盼指点,thanks

以下为测试代码


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class A {
	
	private static String cmd = "ls";//linux os cmd	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub	
		try {
			UseOsCmd(cmd);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void UseOsCmd(String cmd) throws Exception {
		System.out.println("#以下是命令["+cmd+"]的输出:");
		//执行命令
		Runtime runtime = Runtime.getRuntime();
		Process process = runtime.exec(cmd);
		
		//读取命令输出
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				process.getInputStream()));
		String str = "";
		while (reader.read() != -1) {
			str = reader.readLine();
			System.out.println(str);
		}
				
	}

}

   
时间:2008-03-07
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;

public class A {

private static String cmd = "ls > a.txt";//linux os cmd

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
UseOsCmd(cmd);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void UseOsCmd(String cmd) throws Exception {
System.out.println("#以下是命令["+cmd+"]的输出:");
//执行命令
Runtime runtime = Runtime.getRuntime();
runtime.exec(cmd);

//读取命令输出
FileInputStream fis = new FileInputStream("a.txt");
BufferedReader reader = new BufferedReader(
fis);
String str = "";
while((str =bf.readLine()) != null)
System.out.println(str);
}

}

}

请参考^_^
   
0 请登录后投票
时间:2008-03-07
流应该close
   
0 请登录后投票
时间:2008-03-07
继续问一下
在solaris10下执行java A,显示的结果为

#以下是命令[ls]的输出:
.txt
.class
.java
.sh
.txt
ydir


为什么只显示后缀名,而不是显示完整名称
以下是命令行显示的:
-bash-3.00$ ls
1.txt A.class A.java a.sh b.txt mydir

麻烦指教,再次感谢
   
0 请登录后投票
论坛首页 Java版

跳转论坛:
JavaEye推荐