com.google.common.io.Files类的使用及代码示例

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

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

Files介绍

[英]Provides utility methods for working with File.

java.nio.file.Path users will find similar utilities in MoreFiles and the JDK's java.nio.file.Files class.
[中]提供用于处理文件的实用工具方法。
JAVA尼奥。文件Path用户将在MoreFiles和JDK的java中找到类似的实用程序。尼奥。文件文件类。

代码示例

代码示例来源:origin: ronmamo/reflections

public File save(Reflections reflections, String filename) {
  try {
    File file = Utils.prepareFile(filename);
    Files.write(toString(reflections), file, Charset.defaultCharset());
    return file;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: google/guava

@Override
public void setUp() throws IOException {
 rootDir = Files.createTempDir();
}

代码示例来源:origin: google/guava

public void testCopyIdenticalFiles() throws IOException {
 File temp1 = createTempFile();
 Files.write(ASCII, temp1, Charsets.UTF_8);
 File temp2 = createTempFile();
 Files.write(ASCII, temp2, Charsets.UTF_8);
 Files.copy(temp1, temp2);
 assertEquals(ASCII, Files.toString(temp1, Charsets.UTF_8));
}

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

@Override
public String getName()
{
 final String ext = Files.getFileExtension(path);
 return Files.getNameWithoutExtension(path) + (Strings.isNullOrEmpty(ext) ? "" : ("." + ext));
}

代码示例来源:origin: prestodb/presto

public BenchmarkQuery(File file)
    throws IOException
{
  requireNonNull(file, "file is null");
  name = Files.getNameWithoutExtension(file.getName());
  // file can have 2 sections separated by a line of equals signs
  String text = Files.toString(file, StandardCharsets.UTF_8);
  List<String> sections = SECTION_SPLITTER.splitToList(text);
  if (sections.size() == 2) {
    this.tags = ImmutableMap.copyOf(TAGS_SPLITTER.split(sections.get(0)));
    this.sql = sections.get(1);
  }
  else {
    // no tags
    this.tags = ImmutableMap.of();
    this.sql = sections.get(0);
  }
}

代码示例来源:origin: google/guava

public void testAppendString() throws IOException {
 File temp = createTempFile();
 Files.append(I18N, temp, Charsets.UTF_16LE);
 assertEquals(I18N, Files.toString(temp, Charsets.UTF_16LE));
 Files.append(I18N, temp, Charsets.UTF_16LE);
 assertEquals(I18N + I18N, Files.toString(temp, Charsets.UTF_16LE));
 Files.append(I18N, temp, Charsets.UTF_16LE);
 assertEquals(I18N + I18N + I18N, Files.toString(temp, Charsets.UTF_16LE));
}

代码示例来源:origin: dreamhead/moco

@Test
public void should_fire_event() throws IOException {
  runWithConfiguration("event.json");
  File file = folder.newFile();
  System.setOut(new PrintStream(new FileOutputStream(file)));
  assertThat(helper.get(remoteUrl("/event")), is("post_foo"));
  idle(IDLE, TimeUnit.MILLISECONDS);
  assertThat(Files.toString(file, Charset.defaultCharset()), containsString("0XCAFEBABE"));
}

代码示例来源:origin: dreamhead/moco

@Override
  public void run() throws IOException {
    assertThat(helper.postContent(remoteUrl("/proxy"), "proxy"), is("proxy"));
    assertThat(Files.toString(tempFile, Charset.defaultCharset()), containsString("proxy"));
  }
});

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

final List<String> lines = Files.readLines(logFile, Charset.defaultCharset(), new LineProcessor<List<String>>() {
  private List<String> matchedLines = new LinkedList<>();

代码示例来源:origin: org.apache.logging.log4j/log4j-core

public void testNoNulCharacters(final String message, final String expected) throws IOException {
  @SuppressWarnings("resource")
  final LoggerContext loggerContext = loggerContextRule.getLoggerContext();
  final Logger logger = loggerContext.getLogger("com.example");
  logger.error("log:", message);
  loggerContext.stop();
  final File file = new File(FILE_PATH);
  final byte[] contents = Files.toByteArray(file);
  int count0s = 0;
  final StringBuilder sb = new StringBuilder();
  for (int i = 0; i < contents.length; i++) {
    final byte b = contents[i];
    if (b == 0) {
      sb.append(i);
      sb.append(", ");
      count0s++;
    }
  }
  Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s);
  final List<String> readLines = Files.readLines(file, Charset.defaultCharset());
  final String actual = readLines.get(0);
  // Assert.assertTrue(actual, actual.contains(message));
  Assert.assertEquals(actual, expected, actual);
  Assert.assertEquals(1, readLines.size());
}

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

@Test
public void testPushTaskLogDirCreationFails() throws Exception
{
 final File tmpDir = temporaryFolder.newFolder();
 final File logDir = new File(tmpDir, "druid/logs");
 final File logFile = new File(tmpDir, "log");
 Files.write("blah", logFile, StandardCharsets.UTF_8);
 if (!tmpDir.setWritable(false)) {
  throw new RuntimeException("failed to make tmp dir read-only");
 }
 final TaskLogs taskLogs = new FileTaskLogs(new FileTaskLogsConfig(logDir));
 expectedException.expect(IOException.class);
 expectedException.expectMessage("Unable to create task log dir");
 taskLogs.pushTaskLog("foo", logFile);
}

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

@Test
public void testSanity() throws Exception
{
 File baseDir = folder.newFolder("base");
 try (FileSmoosher smoosher = new FileSmoosher(baseDir, 21)) {
  for (int i = 0; i < 20; ++i) {
   File tmpFile = folder.newFile(StringUtils.format("smoosh-%s.bin", i));
   Files.write(Ints.toByteArray(i), tmpFile);
   smoosher.add(StringUtils.format("%d", i), tmpFile);
  }
 }
 validateOutput(baseDir);
}

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

@Test
public void testSimple() throws Exception
{
 final File tmpDir = temporaryFolder.newFolder();
 try {
  final File logDir = new File(tmpDir, "druid/logs");
  final File logFile = new File(tmpDir, "log");
  Files.write("blah", logFile, StandardCharsets.UTF_8);
  final TaskLogs taskLogs = new FileTaskLogs(new FileTaskLogsConfig(logDir));
  taskLogs.pushTaskLog("foo", logFile);
  final Map<Long, String> expected = ImmutableMap.of(0L, "blah", 1L, "lah", -2L, "ah", -5L, "blah");
  for (Map.Entry<Long, String> entry : expected.entrySet()) {
   final byte[] bytes = ByteStreams.toByteArray(taskLogs.streamTaskLog("foo", entry.getKey()).get().openStream());
   final String string = StringUtils.fromUtf8(bytes);
   Assert.assertEquals(StringUtils.format("Read with offset %,d", entry.getKey()), string, entry.getValue());
  }
 }
 finally {
  FileUtils.deleteDirectory(tmpDir);
 }
}

代码示例来源:origin: google/guava

public void testWriteString() throws IOException {
 File temp = createTempFile();
 Files.write(I18N, temp, Charsets.UTF_16LE);
 assertEquals(I18N, Files.toString(temp, Charsets.UTF_16LE));
}

代码示例来源:origin: prestodb/presto

@Test(groups = {LDAP, LDAP_CLI, PROFILE_SPECIFIC_TESTS}, timeOut = TIMEOUT)
public void shouldRunQueryFromFileWithLdap()
    throws IOException
{
  File temporayFile = File.createTempFile("test-sql", null);
  temporayFile.deleteOnExit();
  Files.write("select * from hive.default.nation;\n", temporayFile, UTF_8);
  launchPrestoCliWithServerArgument("--file", temporayFile.getAbsolutePath());
  assertThat(trimLines(presto.readRemainingOutputLines())).containsAll(nationTableBatchLines);
}

代码示例来源:origin: google/guava

private static URL makeJarUrlWithName(String name) throws IOException {
 File fullPath = new File(Files.createTempDir(), name);
 File jarFile = JarFileFinder.pickAnyJarFile();
 Files.copy(jarFile, fullPath);
 return fullPath.toURI().toURL();
}

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

public static void createSourceJsonFile(File sourceJsonFile) throws IOException {
 Files.createParentDirs(sourceJsonFile);
 Files.write(SOURCE_JSON_DOCS, sourceJsonFile, ConfigurationKeys.DEFAULT_CHARSET_ENCODING);
}

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

@Test
public void canOutputSimpleRegionToFile() throws Exception {
 File outputFile = temporaryFolder.newFile("queryOutput.txt");
 FileUtils.deleteQuietly(outputFile);
 CommandResult result = gfsh.executeCommand(
   "query --query='select * from /simpleRegion' --file=" + outputFile.getAbsolutePath());
 assertThat(result.getStatus()).isEqualTo(Result.Status.OK);
 // .statusIsSuccess().containsOutput(outputFile.getAbsolutePath());
 assertThat(outputFile).exists();
 List<String> lines = Files.readLines(outputFile, StandardCharsets.UTF_8);
 assertThat(lines.get(7)).isEqualTo("Result");
 assertThat(lines.get(8)).isEqualTo("--------");
 lines.subList(9, lines.size()).forEach(line -> assertThat(line).matches("value\\d+"));
}

代码示例来源:origin: google/guava

public void testMap_readWrite() throws IOException {
 // Test data
 int size = 1024;
 byte[] expectedBytes = new byte[size];
 byte[] bytes = newPreFilledByteArray(1024);
 // Setup
 File file = createTempFile();
 Files.write(bytes, file);
 Random random = new Random();
 random.nextBytes(expectedBytes);
 // Test
 MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE);
 map.put(expectedBytes);
 // Verify
 byte[] actualBytes = Files.toByteArray(file);
 assertTrue(Arrays.equals(expectedBytes, actualBytes));
}

代码示例来源:origin: google/guava

public void testWriteBytes() throws IOException {
 File temp = createTempFile();
 byte[] data = newPreFilledByteArray(2000);
 Files.write(data, temp);
 assertTrue(Arrays.equals(data, Files.toByteArray(temp)));
 try {
  Files.write(null, temp);
  fail("expected exception");
 } catch (NullPointerException expected) {
 }
}

相关文章