org.apache.commons.io.FileUtils.readFileToString()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(746)

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

FileUtils.readFileToString介绍

[英]Reads the contents of a file into a String using the default encoding for the VM. The file is always closed.
[中]使用VM的默认编码将文件内容读入字符串。文件始终处于关闭状态。

代码示例

代码示例来源:origin: jenkinsci/jenkins

/**
 * Reads the master kill switch from a file.
 *
 * Instead of {@link FileBoolean}, we use a text file so that the admin can prevent Jenkins from
 * writing this to file.
 * @param f File to load
 * @return {@code true} if the file was loaded, {@code false} otherwise
 */
@CheckReturnValue
private boolean loadMasterKillSwitchFile(@Nonnull File f) {
  try {
    if (!f.exists())    return true;
    return Boolean.parseBoolean(FileUtils.readFileToString(f).trim());
  } catch (IOException e) {
    LOGGER.log(WARNING, "Failed to read "+f, e);
    return false;
  }
}

代码示例来源:origin: jenkinsci/jenkins

public String call() throws IOException {
    File f = new File(script);
    if(f.exists())
      return FileUtils.readFileToString(f);

    URL url;
    try {
      url = new URL(script);
    } catch (MalformedURLException e) {
      throw new AbortException("Unable to find a script "+script);
    }
    try (InputStream s = url.openStream()) {
      return IOUtils.toString(s);
    }
  }
}

代码示例来源:origin: jenkinsci/jenkins

protected void execute() {
  File timestampFile = new File(home,".owner");
  long t = timestampFile.lastModified();
  if(t!=0 && lastWriteTime!=0 && t!=lastWriteTime && !ignore) {
    try {
      collidingId = FileUtils.readFileToString(timestampFile);
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Failed to read collision file", e);
    }
    // we noticed that someone else have updated this file.
    // switch GUI to display this error.
    Jenkins.getInstance().servletContext.setAttribute("app",this);
    LOGGER.severe("Collision detected. timestamp="+t+", expected="+lastWriteTime);
    // we need to continue updating this file, so that the other Hudson would notice the problem, too.
  }
  try {
    FileUtils.writeStringToFile(timestampFile, getId());
    lastWriteTime = timestampFile.lastModified();
  } catch (IOException e) {
    // if failed to write, err on the safe side and assume things are OK.
    lastWriteTime=0;
  }
  schedule();
}

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

@Test
public void testReadFileToStringWithEncoding() throws Exception {
  final File file = new File(getTestDirectory(), "read.obj");
  final FileOutputStream out = new FileOutputStream(file);
  final byte[] text = "Hello /u1234".getBytes("UTF8");
  out.write(text);
  out.close();
  final String data = FileUtils.readFileToString(file, "UTF8");
  assertEquals("Hello /u1234", data);
}

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

@Test
public void testFileUtils() throws Exception {
  // Loads file from classpath
  final File file1 = new File(getTestDirectory(), "test.txt");
  final String filename = file1.getAbsolutePath();
  //Create test file on-the-fly (used to be in CVS)
  try (OutputStream out = new FileOutputStream(file1)) {
    out.write("This is a test".getBytes("UTF-8"));
  }
  final File file2 = new File(getTestDirectory(), "test2.txt");
  FileUtils.writeStringToFile(file2, filename, "UTF-8");
  assertTrue(file2.exists());
  assertTrue(file2.length() > 0);
  final String file2contents = FileUtils.readFileToString(file2, "UTF-8");
  assertTrue(
      "Second file's contents correct",
      filename.equals(file2contents));
  assertTrue(file2.delete());
  final String contents = FileUtils.readFileToString(new File(filename), "UTF-8");
  assertEquals("FileUtils.fileRead()", "This is a test", contents);
}

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

@Test
public void testWriteByteArrayToFile_WithAppendOptionFalse_ShouldDeletePreviousFileLines() throws Exception {
  final File file = TestUtils.newFile(getTestDirectory(), "lines.txt");
  FileUtils.writeStringToFile(file, "This line was there before you...");
  FileUtils.writeByteArrayToFile(file, "this is brand new data".getBytes(), false);
  final String expected = "this is brand new data";
  final String actual = FileUtils.readFileToString(file);
  assertEquals(expected, actual);
}

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

@Test
public void testReadFileToStringWithDefaultEncoding() throws Exception {
  final File file = new File(getTestDirectory(), "read.obj");
  final FileOutputStream out = new FileOutputStream(file);
  final byte[] text = "Hello /u1234".getBytes();
  out.write(text);
  out.close();
  final String data = FileUtils.readFileToString(file);
  assertEquals("Hello /u1234", data);
}

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

@Test
public void shouldOverwriteAFileCalledGoPluginActivatorInLibWithOurOwnGoPluginActivatorEvenIfItExists() throws Exception {
  File pluginJarFile = new File(pluginDir, PLUGIN_JAR_FILE_NAME);
  File expectedBundleDirectory = new File(bundleDir, PLUGIN_JAR_FILE_NAME);
  File activatorFileLocation = new File(expectedBundleDirectory, "lib/go-plugin-activator.jar");
  FileUtils.writeStringToFile(activatorFileLocation, "SOME-DATA", UTF_8);
  copyPluginToTheDirectory(pluginDir, PLUGIN_JAR_FILE_NAME);
  GoPluginDescriptor descriptor = GoPluginDescriptor.usingId("testplugin.descriptorValidator", pluginJarFile.getAbsolutePath(), expectedBundleDirectory, true);
  when(goPluginDescriptorBuilder.build(pluginJarFile, true)).thenReturn(descriptor);
  doNothing().when(registry).loadPlugin(descriptor);
  listener.pluginJarAdded(new PluginFileDetails(pluginJarFile, true));
  assertThat(new File(expectedBundleDirectory, "lib/go-plugin-activator.jar").exists(), is(true));
  assertThat(FileUtils.readFileToString(activatorFileLocation, UTF_8), is(not("SOME-DATA")));
}

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

Key loadSecretFileFromFile(String path) throws IOException {
 if (StringUtils.isBlank(path)) {
  throw new IllegalStateException("Secret key not found. Please set the property " + ENCRYPTION_SECRET_KEY_PATH);
 }
 File file = new File(path);
 if (!file.exists() || !file.isFile()) {
  throw new IllegalStateException("The property " + ENCRYPTION_SECRET_KEY_PATH + " does not link to a valid file: " + path);
 }
 String s = FileUtils.readFileToString(file, UTF_8);
 if (StringUtils.isBlank(s)) {
  throw new IllegalStateException("No secret key in the file: " + path);
 }
 return new SecretKeySpec(Base64.decodeBase64(StringUtils.trim(s)), CRYPTO_KEY);
}

代码示例来源:origin: zalando/zalenium

private void setupDashboardFile(File dashboardHtml) throws IOException {
  String dashboard = FileUtils.readFileToString(new File(getCurrentLocalPath(), DASHBOARD_TEMPLATE_FILE), UTF_8);
  dashboard = dashboard.replace("{retentionPeriod}", String.valueOf(retentionPeriod));
  FileUtils.writeStringToFile(dashboardHtml, dashboard, UTF_8);
  CommonProxyUtilities.setFilePermissions(dashboardHtml.toPath());
}

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

@Test
public void testWriteByteArrayToFile_WithOffsetAndLength_WithAppendOptionTrue_ShouldDeletePreviousFileLines() throws Exception {
  final File file = TestUtils.newFile(getTestDirectory(), "lines.txt");
  FileUtils.writeStringToFile(file, "This line was there before you...");
  final byte[] data = "SKIP_THIS_this is brand new data_AND_SKIP_THIS".getBytes(Charsets.UTF_8);
  FileUtils.writeByteArrayToFile(file, data, 10, 22, false);
  final String expected = "this is brand new data";
  final String actual = FileUtils.readFileToString(file, Charsets.UTF_8);
  assertEquals(expected, actual);
}

代码示例来源:origin: jenkinsci/jenkins

static String readSymlink(File cache) throws IOException, InterruptedException {
  synchronized (symlinks) {
    String target = symlinks.get(cache);
    if (target != null) {
      LOGGER.log(Level.FINE, "readSymlink cached {0} → {1}", new Object[] {cache, target});
      return target;
    }
  }
  String target = Util.resolveSymlink(cache);
  if (target==null && cache.exists()) {
    // if this file isn't a symlink, it must be a regular file
    target = FileUtils.readFileToString(cache,"UTF-8").trim();
  }
  LOGGER.log(Level.FINE, "readSymlink {0} → {1}", new Object[] {cache, target});
  synchronized (symlinks) {
    symlinks.put(cache, target);
  }
  return target;
}

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

@Test
public void shouldReplaceJettyXmlIfItDoesNotContainCorrespondingJettyVersionNumber() throws IOException {
  File jettyXml = temporaryFolder.newFile("jetty.xml");
  when(systemEnvironment.getJettyConfigFile()).thenReturn(jettyXml);
  String originalContent = "jetty-v6.2.3\nsome other local changes";
  FileUtils.writeStringToFile(jettyXml, originalContent, UTF_8);
  jetty9Server.replaceJettyXmlIfItBelongsToADifferentVersion(systemEnvironment.getJettyConfigFile());
  assertThat(FileUtils.readFileToString(systemEnvironment.getJettyConfigFile(), UTF_8), is(FileUtils.readFileToString(new File(getClass().getResource("config/jetty.xml").getPath()), UTF_8)));
}

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

@Test
public void shouldReplaceExistingBundledPluginsWithNewPluginsOfSameName() throws Exception {
  File bundledPlugin = new File(directoryForUnzippedPlugins, "bundled/plugin-1.jar");
  setupAgentsPluginFile().withBundledPlugin("plugin-1.jar", "SOME-NEW-CONTENT").done();
  FileUtils.writeStringToFile(bundledPlugin, "OLD-CONTENT", UTF_8);
  agentPluginsInitializer.onApplicationEvent(null);
  assertThat(bundledPlugin.exists(), is(true));
  assertThat(FileUtils.readFileToString(bundledPlugin, UTF_8), is("SOME-NEW-CONTENT"));
}

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

Key loadSecretFileFromFile(@Nullable String path) throws IOException {
 if (StringUtils.isBlank(path)) {
  throw new IllegalStateException("Secret key not found. Please set the property " + CoreProperties.ENCRYPTION_SECRET_KEY_PATH);
 }
 File file = new File(path);
 if (!file.exists() || !file.isFile()) {
  throw new IllegalStateException("The property " + CoreProperties.ENCRYPTION_SECRET_KEY_PATH + " does not link to a valid file: " + path);
 }
 String s = FileUtils.readFileToString(file, UTF_8);
 if (StringUtils.isBlank(s)) {
  throw new IllegalStateException("No secret key in the file: " + path);
 }
 return new SecretKeySpec(Base64.decodeBase64(StringUtils.trim(s)), CRYPTO_KEY);
}

代码示例来源:origin: alibaba/jstorm

@Override
public String getStormRawConf() throws TException {
  try {
    return FileUtils.readFileToString(new File(LoadConf.getStormYamlPath()));
  } catch (IOException ex) {
    throw new TException(ex);
  }
}

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

@Test
public void testWriteByteArrayToFile_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception {
  final File file = TestUtils.newFile(getTestDirectory(), "lines.txt");
  FileUtils.writeStringToFile(file, "This line was there before you...");
  FileUtils.writeByteArrayToFile(file, "this is brand new data".getBytes(), true);
  final String expected = "This line was there before you..."
      + "this is brand new data";
  final String actual = FileUtils.readFileToString(file);
  assertEquals(expected, actual);
}

代码示例来源:origin: alibaba/canal

private LogPosition loadDataFromFile(File dataFile) {
    try {
      if (!dataFile.exists()) {
        return null;
      }

      String json = FileUtils.readFileToString(dataFile, charset.name());
      return JsonUtils.unmarshalFromString(json, LogPosition.class);
    } catch (IOException e) {
      throw new CanalMetaManagerException(e);
    }
  }
}

代码示例来源:origin: apache/hive

@Test
public void testNonAcidOrcFile() throws Exception {
 // Copy data/files/alltypesorc to workDir
 Path baseSrcDir = new Path(System.getProperty("basedir")).getParent();
 Path dataFilesPath = new Path(new Path(baseSrcDir, "data"), "files");
 File origOrcFile = new File(dataFilesPath.toString(), "alltypesorc");
 File testOrcFile = new File(workDir.toString(), "alltypesorc");
 FileUtils.copyFile(origOrcFile, testOrcFile);
 String outputFilename = "fixAcidKeyIndex.out";
 File outFile = new File(workDir.toString(), outputFilename);
 runIndexCheck(new Path(testOrcFile.getPath()), outFile);
 String outputAsString = FileUtils.readFileToString(outFile);
 System.out.println(outputAsString);
 assertTrue(outputAsString.contains("is not an acid file"));
}

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

@Test
public void shouldReplaceExistingExternalPluginsWithNewPluginsOfSameName() throws Exception {
  File externalPlugin = new File(directoryForUnzippedPlugins, "external/plugin-1.jar");
  setupAgentsPluginFile().withExternalPlugin("plugin-1.jar", "SOME-NEW-CONTENT").done();
  FileUtils.writeStringToFile(externalPlugin, "OLD-CONTENT", UTF_8);
  agentPluginsInitializer.onApplicationEvent(null);
  assertThat(externalPlugin.exists(), is(true));
  assertThat(FileUtils.readFileToString(externalPlugin, UTF_8), is("SOME-NEW-CONTENT"));
}

相关文章

FileUtils类方法