开发者

Error in opening text file from src folder in Java

I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments (InputStre开发者_开发知识库am) , Any suggestions ? Thanks

Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);


You can not execute an input-stream, it's just a collection of bytes, not a file.

You should store this file somewhere else inside your project (like a resources folder) and use the path to open the file. Here's how it would look like:

File file = new File("resources/my-file.txt");
String[] command = { "notepad.exe", file.getAbsolutePath() };
Runtime.getRuntime().exec( command );


None of the Runtime.exec methods accept an InputStream

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html


To read a file from an InputStream, use a BufferedReader

BufferedReader reader = new BufferedReader(new InputStreamReader(lic));

String line = reader.readLine()
while(line != null){
    System.out.println(line);
    line = reader.readLine();
}


I think this is what you're trying to do:

ProcessBuilder pb = new ProcessBuilder("notepad", "/path/to/text-file");
Process process = pb.start();

See ProcessBuilder Javadocs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜