3. 执行本机命令(取决于平台)

exec()在操作系统的一个单独进程中执行指定的命令和参数。

private static void readOnlyFileUsingSetReadOnly() throws IOException 
{
	File readOnlyFile = new File("c:/temp/testReadOnly.txt");
	// windows平台
	Runtime.getRuntime().exec("attrib " + "" + readOnlyFile.getAbsolutePath() + "" + " +R");
	// linux
	Runtime.getRuntime().exec("chmod 400 " + "" + readOnlyFile.getAbsolutePath() + "");
}
on  it road.com

使用 java.io.File.setWritable(false) 方法

setWritable()是设置所有者对此抽象路径名的写权限的便捷方法。

private static void readOnlyFileUsingSetWritable() throws IOException 
{
	File readOnlyFile = new File("c:/temp/testReadOnly.txt");
	// 设置只读
	readOnlyFile.setWritable(false);
}

使用File.setReadOnly()使文件只读

setReadOnly()方法标记路径中指定的文件或者目录,以便只允许读取操作。

private static void readOnlyFileUsingNativeCommand() throws IOException 
{
	File readOnlyFile = new File("c:/temp/testReadOnly.txt");

	// 设置只读
	readOnlyFile.setReadOnly();
}
Java 如何设置文件的权限

Java 如何将文件设置为只读?

日期:2020-09-17 00:09:23 来源:oir作者:oir