gpt4 book ai didi

java - 我无法在java中将文本文件设置为只读模式

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:38 25 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 tem=temp.getName();
String line;
PrintWriter out = new PrintWriter(new FileWriter(tem));
//System.out.println(""+filePath);
while ((line = br.readLine()) != null) {
out.println(line);
}
temp.setReadOnly();
String[] cmd = {"notepad",tem};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
// proc.getInputStream();
out.close();
br.close();
//temp.deleteOnExit();
}
catch(IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}

在上面的代码中我无法 setReadonly();命令到临时文件。显示带有所有选项的文件,您可以建议如何使临时文件不被修改,甚至无法保存到其他位置。我只需要在程序运行时显示该文件。在此期间,用户不会更改任何内容,也无法将其保存到其他位置。

最佳答案

我建议在使用它之前关闭该文件(通过记事本):

        PrintWriter out = new PrintWriter(new FileWriter(tem));
//System.out.println(""+filePath);
while ((line = br.readLine()) != null) {
out.println(line);
}
out.close();
temp.setReadOnly();
String[] cmd = {"notepad",tem};
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(cmd);
// proc.getInputStream();

为了避免用户将文件移动到其他位置,您可以在临时文件夹中另外创建临时文件,并将该文件夹设置为只读。但如果用户可以读取,他们通常可以将文件复制到另一个位置。如果我没记错的话,在 Windows 中您可以标记为已读但阻止复制文件(当然通过 Windows)。

关于java - 我无法在java中将文本文件设置为只读模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21599278/

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