gpt4 book ai didi

java临时文件创建但内容写入问题

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:53 26 4
gpt4 key购买 nike

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();

}


}

在上面的代码中创建了临时文件,但我试图在该文件中写入内容,但是当程序执行时,记事本使用临时名称打开,但它给出消息文件不存在,您想创建吗?我需要该临时文件,其文本位于 D:\text\test.txt 位置。请推荐我

最佳答案

好的,这是应该可以工作的更新后的代码。我已经将其编写为 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();

关于java临时文件创建但内容写入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21598338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com