java.io.File.setReadOnly()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(203)

本文整理了Java中java.io.File.setReadOnly()方法的一些代码示例,展示了File.setReadOnly()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.setReadOnly()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:setReadOnly

File.setReadOnly介绍

[英]Equivalent to setWritable(false, false).
[中]等同于可设置写(false,false)。

代码示例

代码示例来源:origin: com.h2database/h2

@Override
public boolean setReadOnly() {
  File f = new File(name);
  return f.setReadOnly();
}

代码示例来源:origin: lealone/Lealone

@Override
public boolean setReadOnly() {
  File f = new File(name);
  return f.setReadOnly();
}

代码示例来源:origin: spotbugs/spotbugs

public void testFilesMethods() throws IOException {
    File f = new File("blah.txt");
    File f2 = new File("blah2.txt");

    // All of these should generate a warning
    f.mkdir();
    f.mkdirs();
    f.delete();
    f.createNewFile();
    f.setLastModified(1L);
    f.setReadOnly();
    f.renameTo(f2);
  }
}

代码示例来源:origin: jphp-group/jphp

@Signature
public Memory setReadOnly(Environment env, Memory... args){
  return file.setReadOnly() ? Memory.TRUE : Memory.FALSE;
}

代码示例来源:origin: robolectric/robolectric

@Before
public void setUp() throws Exception {
 file = new File(ApplicationProvider.getApplicationContext().getFilesDir(), "test");
 FileOutputStream os = new FileOutputStream(file);
 os.close();
 readOnlyFile =
   new File(ApplicationProvider.getApplicationContext().getFilesDir(), "test_readonly");
 os = new FileOutputStream(readOnlyFile);
 os.write(READ_ONLY_FILE_CONTENTS);
 os.close();
 assertThat(readOnlyFile.setReadOnly()).isTrue();
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testCanRead() throws Exception {
  final File readOnlyFile = new File(getTestDirectory(), "read-only-file1.txt");
  if (!readOnlyFile.getParentFile().exists()) {
    throw new IOException("Cannot create file " + readOnlyFile
        + " as the parent directory does not exist");
  }
  try (final BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(readOnlyFile))){
    TestUtils.generateTestData(output, 32);
  }
  readOnlyFile.setReadOnly();
  assertFiltering(CanReadFileFilter.CAN_READ,  readOnlyFile, true);
  assertFiltering(CanReadFileFilter.CANNOT_READ,  readOnlyFile, false);
  assertFiltering(CanReadFileFilter.READ_ONLY, readOnlyFile, true);
  readOnlyFile.delete();
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testCanWrite() throws Exception {
  final File readOnlyFile = new File(getTestDirectory(), "read-only-file2.txt");
  if (!readOnlyFile.getParentFile().exists()) {
    throw new IOException("Cannot create file " + readOnlyFile
        + " as the parent directory does not exist");
  }
  try (final BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(readOnlyFile))){
    TestUtils.generateTestData(output, 32);
  }
  readOnlyFile.setReadOnly();
  assertFiltering(CanWriteFileFilter.CAN_WRITE,    getTestDirectory(), true);
  assertFiltering(CanWriteFileFilter.CANNOT_WRITE, getTestDirectory(), false);
  assertFiltering(CanWriteFileFilter.CAN_WRITE,    readOnlyFile, false);
  assertFiltering(CanWriteFileFilter.CANNOT_WRITE, readOnlyFile, true);
  readOnlyFile.delete();
}

代码示例来源:origin: SonarSource/sonarqube

@Test
 public void if_file_is_not_writable_ISE_must_be_thrown() throws IOException {
  File yamlFile = temp.newFile();
  yamlFile.setReadOnly();

  expectedException.expect(IllegalStateException.class);
  expectedException.expectMessage("Cannot write Elasticsearch yml settings file");

  new EsYmlSettings(new HashMap<>()).writeToYmlSettingsFile(yamlFile);
 }
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Tests the {@link FileUtils#getLocalFileMode(String)}} method.
 */
@Test
public void getLocalFileMode() throws IOException {
 File tmpDir = mTestFolder.newFolder("dir");
 File tmpFile777 = mTestFolder.newFile("dir/0777");
 tmpFile777.setReadable(true, false /* owner only */);
 tmpFile777.setWritable(true, false /* owner only */);
 tmpFile777.setExecutable(true, false /* owner only */);
 File tmpFile755 = mTestFolder.newFile("dir/0755");
 tmpFile755.setReadable(true, false /* owner only */);
 tmpFile755.setWritable(false, false /* owner only */);
 tmpFile755.setExecutable(true, false /* owner only */);
 tmpFile755.setWritable(true, true /* owner only */);
 File tmpFile444 = mTestFolder.newFile("dir/0444");
 tmpFile444.setReadOnly();
 assertEquals((short) 0777, FileUtils.getLocalFileMode(tmpFile777.getPath()));
 assertEquals((short) 0755, FileUtils.getLocalFileMode(tmpFile755.getPath()));
 assertEquals((short) 0444, FileUtils.getLocalFileMode(tmpFile444.getPath()));
 // Delete all of these.
 FileUtils.deletePathRecursively(tmpDir.getAbsolutePath());
}

代码示例来源:origin: voldemort/voldemort

@Test
public void testDisableStoreVersionOnReadOnlyStorage() {
  // Validate that state got synced properly from the filesystem
  Assert.assertFalse("Did not expect to have any store version disabled.",
            storeVersionManager.hasAnyDisabledVersion());
  // Simulate the filesystem becoming read-only underneath us
  version0.setReadOnly();
  // Disable a store version
  try {
    storeVersionManager.disableStoreVersion(0);
    Assert.fail("Did not get a PersistenceFailureException when trying to disableStoreVersion on a read-only filesystem.");
  } catch (PersistenceFailureException e) {
    // expected
  }
  // Validate that the in-memory state changed accordingly
  Assert.assertTrue("Expected in-memory state to have some store version disabled.",
           storeVersionManager.hasAnyDisabledVersion());
  Assert.assertTrue("Expected in-memory state to have store version 1 enabled.",
           storeVersionManager.isCurrentVersionEnabled());
  // Verify that another instance of StoreVersionManager, freshly synced from disk, does NOT have proper state.
  StoreVersionManager storeVersionManager2 = new StoreVersionManager(rootDir, null);
  storeVersionManager2.syncInternalStateFromFileSystem(false);
  Assert.assertFalse("Expected persistent state to have no version disabled.",
           storeVersionManager2.hasAnyDisabledVersion());
}

代码示例来源:origin: apache/incubator-druid

@Test
public void testIOExceptionDuringLookupPersist() throws IOException
{
 File directory = temporaryFolder.newFolder();
 LookupSnapshotTaker lookupSnapshotTaker = new LookupSnapshotTaker(mapper, directory.getAbsolutePath());
 File snapshotFile = lookupSnapshotTaker.getPersistFile(TIER1);
 Assert.assertFalse(snapshotFile.exists());
 Assert.assertTrue(snapshotFile.createNewFile());
 Assert.assertTrue(snapshotFile.setReadOnly());
 Assert.assertTrue(snapshotFile.getParentFile().setReadOnly());
 LookupBean lookupBean = new LookupBean(
   "name",
   null,
   new LookupExtractorFactoryContainer(
     "v1",
     new MapLookupExtractorFactory(
       ImmutableMap.of(
         "key",
         "value"
       ), true
     )
   )
 );
 List<LookupBean> lookupBeanList = Collections.singletonList(lookupBean);
 expectedException.expect(ISE.class);
 expectedException.expectMessage("Exception during serialization of lookups");
 lookupSnapshotTaker.takeSnapshot(TIER1, lookupBeanList);
}

代码示例来源:origin: haraldk/TwelveMonkeys

@Override
public boolean setReadOnly() {
  return target.setReadOnly();
}

代码示例来源:origin: spring-projects/spring-batch

@Test
public void testOpenWithNonWritableFile() throws Exception {
  writer = new FlatFileItemWriter<>();
  writer.setLineAggregator(new PassThroughLineAggregator<>());
  FileSystemResource file = new FileSystemResource("build/no-such-file.foo");
  writer.setResource(file);
  new File(file.getFile().getParent()).mkdirs();
  file.getFile().createNewFile();
  assertTrue("Test file must exist: " + file, file.exists());
  assertTrue("Test file set to read-only: " + file, file.getFile().setReadOnly());
  assertFalse("Should be readonly file: " + file, file.getFile().canWrite());
  writer.afterPropertiesSet();
  try {
    writer.open(executionContext);
    fail("Expected IllegalStateException");
  }
  catch (IllegalStateException e) {
    String message = e.getMessage();
    assertTrue("Message does not contain 'writable': " + message, message.indexOf("writable") >= 0);
  }
}

代码示例来源:origin: typ0520/fastdex

out.close();
if (!tmp.setReadOnly()) {
  throw new IOException("Failed to mark readonly \"" + tmp.getAbsolutePath() +
      "\" (tmp of \"" + extractTo.getAbsolutePath() + "\")");

代码示例来源:origin: org.eclipse.jgit/org.eclipse.jgit

/** {@inheritDoc} */
@Override
public PackLock parse(ProgressMonitor receiving, ProgressMonitor resolving)
    throws IOException {
  tmpPack = File.createTempFile("incoming_", ".pack", db.getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
  tmpIdx = new File(db.getDirectory(), baseName(tmpPack) + ".idx"); //$NON-NLS-1$
  try {
    out = new RandomAccessFile(tmpPack, "rw"); //$NON-NLS-1$
    super.parse(receiving, resolving);
    out.seek(packEnd);
    out.write(packHash);
    out.getChannel().force(true);
    out.close();
    writeIdx();
    tmpPack.setReadOnly();
    tmpIdx.setReadOnly();
    return renameAndOpenPack(getLockMessage());
  } finally {
    if (def != null)
      def.end();
    try {
      if (out != null && out.getChannel().isOpen())
        out.close();
    } catch (IOException closeError) {
      // Ignored. We want to delete the file.
    }
    cleanupTemporaryFiles();
  }
}

代码示例来源:origin: palantir/atlasdb

@Test
public void testWithFileWithInvalidMissingDir() throws Exception {
  String inputFileString = "readonly-dir/missing-dir/test.timestamp";
  File inputFile = new File(inputFileString);
  File readOnlyDir = inputFile.getParentFile().getParentFile();
  Files.createDirectory(readOnlyDir.toPath());
  assertThat(readOnlyDir.setReadOnly()).isTrue();
  assertThatThrownBy(() -> runAndVerifyCliForFile(inputFileString))
      .isInstanceOf(RuntimeException.class)
      .hasCauseExactlyInstanceOf(AccessDeniedException.class);
}

代码示例来源:origin: aws-amplify/aws-sdk-android

@Test(expected = IOException.class)
public void test_WhenFileSystemReadOnlyAndFileNotExists_createFile_ThrowsIOException() throws IOException{
  File testFileSetup = new File(rootTestDirectory, TEST_FILE_NAME);
  testFileSetup.delete();
  Assert.assertFalse(testFileSetup.exists());
  rootTestDirectory.setReadOnly();
  try {
    File testFile = target.createFile(TEST_FILE_NAME);
  } catch (IOException e) {
    throw e;
  }
  finally {
    rootTestDirectory.setWritable(true);
  }
}

代码示例来源:origin: aws-amplify/aws-sdk-android

@Test
  public void test_WhenFileSystemReadOnlyAndFileExists_deleteFile_ReturnsFalseNoException() throws IOException{
    File testFileSetup = new File(rootTestDirectory, TEST_FILE_NAME);
    testFileSetup.delete();
    testFileSetup.createNewFile();
    Assert.assertTrue(testFileSetup.isFile());

    File testFile = new File(rootTestDirectory, TEST_FILE_NAME);
    Assert.assertTrue(testFile.exists());

    rootTestDirectory.setReadOnly();

    Assert.assertFalse(target.deleteFile(testFile));
    Assert.assertTrue(testFile.exists());
    rootTestDirectory.setWritable(true);
  }
}

代码示例来源:origin: jbake-org/jbake

/**
 * Primary intention is to extend test cases to increase coverage.
 *
 * @throws Exception
 */
@Test
public void testWriteProtected() throws Exception {
  File assets = new File(config.getSourceFolder(), "assets");
  File css = new File(folder.toFile(),"css");
  css.mkdir();
  final File cssFile = new File(css, "bootstrap.min.css");
  FileUtils.touch(cssFile);
  cssFile.setReadOnly();
  config.setAssetFolder(assets);
  config.setDestinationFolder(folder.toFile());
  Asset asset = new Asset(config);
  asset.copy();
  cssFile.setWritable(true);
  Assertions.assertFalse(asset.getErrors().isEmpty(), "At least one error during copy expected");
}

代码示例来源:origin: aws-amplify/aws-sdk-android

@Test
public void
    testWhenRecordssFileIsMissingAndRecordssDirectoryIsReadOnly_error() throws IOException {
  File kinesisDirectory = null;
  try {
    File eventDirectory = null;
    FileManager fileManager = new FileManager(TEST_DIRECTORY);
    FileRecordStore recordStore = new FileRecordStore(TEST_DIRECTORY,
        RECORDER_FILE_NAME, MAX_STORAGE_SIZE);
    kinesisDirectory =
        fileManager.createDirectory(Constants.RECORDS_DIRECTORY);
    File recordsFile = new File(eventDirectory, Constants.RECORDS_FILE_NAME);
    fileManager.deleteFile(recordsFile);
    kinesisDirectory.setReadOnly();
    recordStore.put("2");
  } finally {
    if (kinesisDirectory != null && kinesisDirectory.exists()) {
      kinesisDirectory.setWritable(true);
      kinesisDirectory.delete();
    }
  }
}

相关文章