package com.studytrails.tutorials.springremotingrmiserver;
import java.lang.Object;
import java.awt.Desktop;
import java.io.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class GreetingServiceImpl implements GreetingService {
@Override
public String getGreeting(String name) {
return "Hello " + name + "!";
}
public String getText()
{
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[]{"spring-config-server.xml"});
Resource resource = appContext.getResource("file:D:\\text\\test.txt");
StringBuilder builder = new StringBuilder();
try{
InputStream is = resource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
File temp=File.createTempFile("output", ".tmp");
String filePath=temp.getAbsolutePath();
System.out.println(""+filePath);
String line;
PrintWriter out = new PrintWriter(new FileWriter(temp));
//System.out.println(""+filePath);
while ((line = br.readLine()) != null) {
out.println(line);
}
String tem=temp.getName();
//temp.setReadOnly();
String[] cmd = {"notepad",tem};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
out.close();
br.close();
temp.deleteOnExit();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
}
在上面的代码中创建了临时文件,但我试图在该文件中写入内容,但是当程序执行notepad时,使用临时名称打开但是它提供的消息文件不存在你想要创建。我需要该文本存在于D:\ text \ test.txt位置的临时文件。请建议我
答案 0 :(得分:0)
好的,这里应该有更新的代码。我把它写成一个java程序,但它正在工作。你的主要问题是你在进程打开后正在调用temp.deleteOnExit();
。您必须等待该过程完成,否则主线程将在记事本打开之前删除该文件。也可以使用out.write(line);
希望它有所帮助。
String line;
PrintWriter out = new PrintWriter(new FileWriter(temp));
while ((line = br.readLine()) != null) {
out.write(line);
}
out.flush();
out.close();
br.close();
String[] cmd = { "notepad", filePath };
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
out.close();
br.close();
try {
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
temp.deleteOnExit();