com.google.common.io.Files.readLines()方法的使用及代码示例

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

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

Files.readLines介绍

[英]Reads all of the lines from a file. The lines do not include line-termination characters, but do include other leading and trailing whitespace.

This method returns a mutable List. For an ImmutableList, use Files.asCharSource(file, charset).readLines().

java.nio.file.Path equivalent: java.nio.file.Files#readAllLines(java.nio.file.Path,Charset).
[中]读取文件中的所有行。这些行不包含行终止字符,但包含其他前导和尾随空格。
此方法返回一个可变列表。对于不可变列表,请使用文件。asCharSource(文件,字符集)。readLines()。
JAVA尼奥。文件路径等价物:java。尼奥。文件文件#readAllLines(java.nio.file.Path,字符集)。

代码示例

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

private ProcMountsEntry getMountEntry(final File procMounts, final String cgroup)
{
 final List<String> lines;
 try {
  lines = Files.readLines(procMounts, StandardCharsets.UTF_8);
 }
 catch (IOException e) {
  throw new RuntimeException(e);
 }
 for (final String line : lines) {
  final ProcMountsEntry entry = ProcMountsEntry.parse(line);
  if (CGROUP_TYPE.equals(entry.type) && entry.options.contains(cgroup)) {
   return entry;
  }
 }
 throw new RE("Cgroup [%s] not found", cgroup);
}

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

private PidCgroupEntry getCgroupEntry(final File procCgroup, final String cgroup)
{
 final List<String> lines;
 try {
  lines = Files.readLines(procCgroup, StandardCharsets.UTF_8);
 }
 catch (IOException e) {
  throw new RuntimeException(e);
 }
 for (final String line : lines) {
  if (line.startsWith("#")) {
   continue;
  }
  final PidCgroupEntry entry = PidCgroupEntry.parse(line);
  if (entry.controllers.contains(cgroup)) {
   return entry;
  }
 }
 throw new RE("Hierarchy for [%s] not found", cgroup);
}

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

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

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

public RecoveryFile() throws IOException
{
  if (!StringUtils.isNullOrEmpty(arguments.exportRecoveryFile))
  {
    recoveryFile = new File(arguments.exportRecoveryFile);
    logger.info("Tracking exported metric names in " + recoveryFile.getAbsolutePath());
    if (recoveryFile.exists())
    {
      logger.info("Skipping metrics found in " + recoveryFile.getAbsolutePath());
      List<String> list = Files.readLines(recoveryFile, Charset.defaultCharset());
      metricsExported.addAll(list);
    }
    writer = new PrintWriter(new FileOutputStream(recoveryFile, true));
  }
}

代码示例来源: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: xtuhcy/gecco

public FileProxys() {
  try {
    proxys = new ConcurrentHashMap<String, Proxy>();
    proxyQueue = new ConcurrentLinkedQueue<Proxy>();
    URL url = Resources.getResource("proxys");
    File file = new File(url.getPath());
    List<String> lines = Files.readLines(file, Charsets.UTF_8);
    if(lines.size() > 0) {
      for(String line : lines) {
        line = line.trim();
        if(line.startsWith("#")) {
          continue;
        }
        String[] hostPort = line.split(":");
        if(hostPort.length == 2) {
          String host = hostPort[0];
          int port = NumberUtils.toInt(hostPort[1], 80);
          addProxy(host, port);
        }
      }
    }
  } catch(Exception ex) {
    log.info("proxys not load");
  }
}

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

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

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

@Test
public void canOutputComplexRegionToFile() throws Exception {
 File outputFile = temporaryFolder.newFile("queryOutput.txt");
 FileUtils.deleteQuietly(outputFile);
 gfsh.executeAndAssertThat(
   "query --query='select c.name, c.address from /complexRegion c' --file="
     + outputFile.getAbsolutePath())
   .statusIsSuccess().containsOutput(outputFile.getAbsolutePath());
 assertThat(outputFile).exists();
 List<String> lines = Files.readLines(outputFile, StandardCharsets.UTF_8);
 assertThat(lines.get(7)).containsPattern("name\\s+\\|\\s+address");
 lines.subList(9, lines.size())
   .forEach(line -> assertThat(line).matches("name\\d+.*\"city\":\"Hometown\".*"));
}

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

private Map<String, Integer> parseCounts(File file) throws IOException {
 Map<String, Integer> counts = Maps.newHashMap();
 for (String line : Files.readLines(file, Charsets.UTF_8)) {
  List<String> split = Splitter.on("\t").splitToList(line);
  counts.put(split.get(0), Integer.parseInt(split.get(1)));
 }
 return counts;
}

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

public void testLineReading() throws IOException {
 File temp = createTempFile();
 assertNull(Files.readFirstLine(temp, Charsets.UTF_8));
 assertTrue(Files.readLines(temp, Charsets.UTF_8).isEmpty());
 PrintWriter w = new PrintWriter(Files.newWriter(temp, Charsets.UTF_8));
 w.println("hello");
 w.println("");
 w.println(" world  ");
 w.println("");
 w.close();
 assertEquals("hello", Files.readFirstLine(temp, Charsets.UTF_8));
 assertEquals(
   ImmutableList.of("hello", "", " world  ", ""), Files.readLines(temp, Charsets.UTF_8));
 assertTrue(temp.delete());
}

代码示例来源:origin: Netflix/Priam

try {
  final File srcFile = new File(config.getCassHome() + AUDIT_LOG_FILE);
  final List<String> lines = Files.readLines(srcFile, Charset.defaultCharset());
  final File backupFile =
      new File(

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

assertThat(Files.readLines(temp, Charsets.UTF_8, collect)).isEmpty();
w.println("");
w.close();
Files.readLines(temp, Charsets.UTF_8, collect);
assertThat(collect.getResult()).containsExactly("hello", "", " world  ", "").inOrder();
Files.readLines(temp, Charsets.UTF_8, collectNonEmptyLines);
assertThat(collectNonEmptyLines.getResult()).containsExactly("hello", " world  ").inOrder();

代码示例来源: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: glowroot/glowroot

private static List<String> readPropertiesFile(File propFile) throws IOException {
  // properties files must be ISO_8859_1
  return Files.readLines(propFile, ISO_8859_1);
}

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

private static String readBenchmarkServerUri() {
  try {
    for (String line : Files.readLines(new File("../scripts/benchmarks/servers.txt"),
        Charset.forName("UTF-8"))) {
      if (line.startsWith("CLIENT")) {
        String hostname = StringUtils.split(line, '=')[1];
        return "http://" + hostname + ":" + BENCHMARK_SERVER_PORT;
      }
    }
    throw new IllegalStateException("CLIENT declaration not found in servers.txt");
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: KylinOLAP/Kylin

protected static List<String> getParameterFromFile(File sqlFile) throws IOException {
  String sqlFileName = sqlFile.getAbsolutePath();
  int prefixIndex = sqlFileName.lastIndexOf(".sql");
  String dataFielName = sqlFileName.substring(0, prefixIndex) + ".dat";
  File dataFile = new File(dataFielName);
  List<String> parameters = Files.readLines(dataFile, Charset.defaultCharset());
  return parameters;
}

代码示例来源:origin: ahmetaa/zemberek-nlp

public CharNgramCountModel getCountModel(ModelTrainData modelTrainData) throws IOException {
 CharNgramCountModel countModel = new CharNgramCountModel(modelTrainData.modelId,
   modelTrainData.order);
 for (File file : modelTrainData.modelFiles) {
  System.out.println("Processing file:" + file);
  int ignoredCount = 0;
  Set<String> lines = new HashSet<>(com.google.common.io.Files.readLines(file, Charsets.UTF_8));
  for (String line : lines) {
   line = line.toLowerCase();
   boolean ignore = false;
   for (String ignoreWord : ignoreWords) {
    if (line.contains(ignoreWord)) {
     ignore = true;
     ignoredCount++;
     break;
    }
   }
   if (!ignore) {
    line = LanguageIdentifier.preprocess(line);
    countModel.addGrams(line);
   }
  }
  System.out.println("Ignored lines for " + file + " : " + ignoredCount);
 }
 countModel.applyCutOffs(modelTrainData.cutOffs);
 countModel.dumpGrams(1);
 return countModel;
}

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

:new File(BenchmarkOptions.OUTPUT.get(cli))
                     );
List<String> lines = Files.readLines(expressionsFile, Charset.defaultCharset());
Map<String, Object> variables = new HashMap<>();
if (variablesFile.isPresent()) {

代码示例来源:origin: MinecraftForge/ForgeGradle

public void buildSrg(File inSrg, File outSrg) throws IOException
{
  // build the SRG
  
  // delete if existing
  if (outSrg.isFile())
    outSrg.delete();
  // rewrite it.
  String fixed = Files.readLines(inSrg, Charset.defaultCharset(), new SrgLineProcessor(clsMap, access));
  Files.write(fixed.getBytes(), outSrg);
}

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

protected void doReadConfigInheritance(String label, String entityId) throws Exception {
  String mementoFilename = "config-inheritance-"+label+"-"+entityId;
  origMemento = Streams.readFullyString(getClass().getResourceAsStream(mementoFilename));
  
  File persistedEntityFile = new File(mementoDir, Os.mergePaths("entities", entityId));
  Files.write(origMemento.getBytes(), persistedEntityFile);
  
  // we'll make assertions on what we've loaded
  rebind();
  rebindedApp = (Application) newManagementContext.lookup(entityId);
  
  // we'll also make assertions on the contents written out
  RebindTestUtils.waitForPersisted(mgmt());
  newMemento = Joiner.on("\n").join(Files.readLines(persistedEntityFile, Charsets.UTF_8));
}

相关文章