原文: 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()方法

  1. private static void readOnlyFileUsingNativeCommand() throws IOException
  2. {
  3. File readOnlyFile = new File("c:/temp/testReadOnly.txt");
  4. //Mark it read only
  5. readOnlyFile.setReadOnly();
  6. if (readOnlyFile.exists())
  7. {
  8. readOnlyFile.delete();
  9. }
  10. readOnlyFile.createNewFile();
  11. }

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

  1. private static void readOnlyFileUsingSetWritable() throws IOException
  2. {
  3. File readOnlyFile = new File("c:/temp/testReadOnly.txt");
  4. if (readOnlyFile.exists())
  5. {
  6. readOnlyFile.delete();
  7. }
  8. readOnlyFile.createNewFile();
  9. //Mark it read only
  10. readOnlyFile.setWritable(false);
  11. }

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

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

祝您学习愉快!