Java 创建只读文件示例

Java 创建只读文件示例

原文: https://howtodoinjava.com/java/io/how-to-make-a-file-read-only-in-java/

要使文件在 Java 中只读,可以使用以下方法之一。 使用Runtime.getRuntime().exec()的第三种方法是特定于平台的,因为您会将命令作为参数传递给它。 其余两种方法在大多数情况下都可以正常工作。

如果您想更改 Linux/unix 特定的文件属性,例如 使用chmod 775,则 java 不提供任何方法。 您应使用Runtime.getRuntime().exec()来使用第三种方法。

1)使用java.io.File.setReadOnly()方法

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

	//Mark it read only
	readOnlyFile.setReadOnly();

	if (readOnlyFile.exists()) 
	{
		readOnlyFile.delete();
	}
	readOnlyFile.createNewFile();
}

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

private static void readOnlyFileUsingSetWritable() throws IOException 
{
	File readOnlyFile = new File("c:/temp/testReadOnly.txt");
	if (readOnlyFile.exists()) 
	{
		readOnlyFile.delete();
	}
	readOnlyFile.createNewFile();

	//Mark it read only
	readOnlyFile.setWritable(false);
}

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

private static void readOnlyFileUsingSetReadOnly() throws IOException 
{
	File readOnlyFile = new File("c:/temp/testReadOnly.txt");
	//Mark it read only in windows
	Runtime.getRuntime().exec("attrib " + "" + readOnlyFile.getAbsolutePath() + "" + " +R");
}

祝您学习愉快!