[英]Text file read only is not working in java temp.setReadonly() is not working
package com.studytrails.tutorials.springremotingrmiserver;
import java.lang.Object;
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");
temp.setReadOnly();
String filePath=temp.getAbsolutePath();
// System.out.println(""+filePath);
String line;
PrintWriter out = new PrintWriter(new FileWriter("temp"));
while ((line = br.readLine()) != null) {
//System.out.println(line);
out.println(line);
//br.close();
}
RandomAccessFile file = new RandomAccessFile(temp, "r");
String[] cmd = {"notepad" , "temp"};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
out.close();
br.close();
temp.deleteOnExit();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
}
在此代码中temp.setReadonly()
方法不起作用,它以所有访问权限打开文件,我该如何控制临时文件的访问权限,请验证它并告诉我如何解决该问题。 在这里,我试图以只读模式打开文件,该文件位于临时路径中,但是代码打开了文本文档,但未以只读模式打开。 我该如何更改
您的代码是错误的
output.tmp
的文件,并将其设置为只读 temp
的文件 在第1步中打开的文件是只读文件,但在其余代码中则未使用该文件,该文件对一个完全不同的文件进行操作。
另一个技巧永远不要自己构造ApplicationContext
,除非它用于引导应用程序。 实现ApplicationContextAware
或创建一个实例变量来保存ApplicationContext
并在其上放置@Autowired
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.