java.nio.file.Files.readAllLines()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(333)

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

Files.readAllLines介绍

暂无

代码示例

代码示例来源:origin: Graylog2/graylog2-server

private String read() throws IOException {
  final List<String> lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8);
  return lines.size() > 0 ? lines.get(0) : "";
}

代码示例来源:origin: googleapis/google-cloud-java

public static void main(String... args) throws IOException {
  Path path = Paths.get(URI.create("gs://bucket/lolcat.csv"));
  List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
 }
}

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

private List<String> readHostsFromFile(String filename)
  throws IOException {
 List<String> hosts = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
 return hostNameToInstanceNames(hosts);
}

代码示例来源:origin: confluentinc/ksql

private static String loadScript(final String filePath) {
  try {
   return Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8).stream()
     .collect(Collectors.joining(System.lineSeparator()));
  } catch (IOException e) {
   throw new KsqlException("Failed to read file: " + filePath, e);
  }
 }
}

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

/**
 * @return List of servers from the exclude file in format 'hostname:port'.
 */
private List<String> readExcludes(String excludeFile) throws IOException {
 List<String> excludeServers = new ArrayList<>();
 if (excludeFile == null) {
  return excludeServers;
 } else {
  try {
   Files.readAllLines(Paths.get(excludeFile)).stream().map(String::trim)
     .filter(((Predicate<String>) String::isEmpty).negate()).map(String::toLowerCase)
     .forEach(excludeServers::add);
  } catch (IOException e) {
   LOG.warn("Exception while reading excludes file, continuing anyways", e);
  }
  return excludeServers;
 }
}

代码示例来源:origin: hs-web/hsweb-framework

@GetMapping("/read")
@ApiOperation("读取文本文件内容")
@SneakyThrows
@Authorize(action = "read", description = "读取文件")
public ResponseMessage<String> read(@RequestParam String file) {
  File fileInfo = new File(file);
  if (!fileInfo.exists()) {
    return ResponseMessage.error(404,"文件不存在");
  }
  if (fileInfo.length() > 2 * 1024 * 1024 * 1024L) {
    return ResponseMessage.error(500, "文件过大,无法读取");
  }
  List<String> list = Files.readAllLines(Paths.get(file));
  StringJoiner joiner = new StringJoiner("\n");
  list.forEach(joiner::add);
  return ResponseMessage.ok(joiner.toString());
}

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

/**
 * Reads a list of nodes from given file name ignoring comments and empty lines.
 * Can be used to read conf/workers or conf/masters.
 * @param fileName name of a file that contains the list of the nodes
 * @return list of the node names, null when file fails to read
 */
public static List<String> readNodeList(String fileName) {
 String confDir = ServerConfiguration.get(PropertyKey.CONF_DIR);
 List<String> lines;
 try {
  lines = Files.readAllLines(Paths.get(confDir, fileName), StandardCharsets.UTF_8);
 } catch (IOException e) {
  System.err.format("Failed to read file %s/%s.%n", confDir, fileName);
  return null;
 }
 List<String> nodes = new ArrayList<>();
 for (String line : lines) {
  String node = line.trim();
  if (node.startsWith("#") || node.length() == 0) {
   continue;
  }
  nodes.add(node);
 }
 return nodes;
}

代码示例来源:origin: real-logic/agrona

private static void expandPrimitiveSpecialisedClass(final String packageName, final String className)
  throws IOException
{
  final Path inputPath = Paths.get(SOURCE_DIRECTORY, packageName, className + SUFFIX);
  final Path outputDirectory = Paths.get(GENERATED_DIRECTORY, packageName);
  Files.createDirectories(outputDirectory);
  final List<String> contents = Files.readAllLines(inputPath, UTF_8);
  for (final Substitution substitution : SUBSTITUTIONS)
  {
    final String substitutedFileName = substitution.substitute(className);
    final List<String> substitutedContents = contents
      .stream()
      .map(substitution::checkedSubstitute)
      .collect(toList());
    final Path outputPath = Paths.get(GENERATED_DIRECTORY, packageName, substitutedFileName + SUFFIX);
    Files.write(outputPath, substitutedContents, UTF_8);
  }
}

代码示例来源:origin: cbeust/testng

private void readAndPrintFile(String fileName) {
 try {
  Files.readAllLines(Paths.get(fileName)).forEach(line -> log("  " + line, Project.MSG_INFO));
 } catch (IOException ex) {
  LOGGER.error(ex.getMessage(), ex);
 }
}

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

/**
 * Includes OS cache and free swap.
 *
 * @return the total free memory size of the OS. 0 if there is an error or the OS doesn't support
 * this memory check.
 */
long getOsTotalFreeMemorySize() {
 if (!Files.isRegularFile(Paths.get(MEM_INFO_FILE))) {
  // Mac doesn't support /proc/meminfo for example.
  return 0;
 }
 final List<String> lines;
 // The file /proc/meminfo is assumed to contain only ASCII characters.
 // The assumption is that the file is not too big. So it is simpler to read the whole file
 // into memory.
 try {
  lines = Files.readAllLines(Paths.get(MEM_INFO_FILE), StandardCharsets.UTF_8);
 } catch (final IOException e) {
  final String errMsg = "Failed to open mem info file: " + MEM_INFO_FILE;
  logger.error(errMsg, e);
  return 0;
 }
 return getOsTotalFreeMemorySizeFromStrings(lines);
}

代码示例来源:origin: crossoverJie/cim

@Override
  public String query(String key) {
    StringBuilder sb = new StringBuilder();

    Path path = Paths.get(appConfiguration.getMsgLoggerPath() + appConfiguration.getUserName() + "/");

    try {
      Stream<Path> list = Files.list(path);
      List<Path> collect = list.collect(Collectors.toList());
      for (Path file : collect) {
        List<String> strings = Files.readAllLines(file);
        for (String msg : strings) {
          if (msg.trim().contains(key)) {
            sb.append(msg).append("\n");
          }
        }

      }
    } catch (IOException e) {
      LOGGER.info("IOException", e);
    }

    return sb.toString().replace(key, "\033[31;4m" + key + "\033[0m");
  }
}

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

private List<String> getScriptLines(Resource scriptResource) throws IOException {
  URI uri = scriptResource.getURI();
  initFileSystem(uri);
  return Files.readAllLines(Paths.get(uri), StandardCharsets.UTF_8);
}

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

@DataProvider(name = "1000points")
public Object[][] points1000()
    throws IOException
{
  Path filePath = Paths.get(this.getClass().getClassLoader().getResource("1000_points.txt").getPath());
  List<String> points = Files.readAllLines(filePath);
  return new Object[][] {
      {
          "1000points",
          "POLYGON ((0.7642699 0.000490129, 0.92900103 0.005068898, 0.97419316 0.019917727, 0.99918157 0.063635945, 0.9997078 0.10172784, 0.9973114 0.41161585, 0.9909166 0.94222105, 0.9679412 0.9754768, 0.95201814 0.9936909, 0.44082636 0.9999601, 0.18622541 0.998157, 0.07163471 0.98902994, 0.066090584 0.9885783, 0.024429202 0.9685611, 0.0044354796 0.8878008, 0.0025004745 0.81172496, 0.0015820265 0.39900982, 0.001614511 0.00065791607, 0.7642699 0.000490129))",
          points.toArray(new String[0]),
      },
  };
}

代码示例来源:origin: awsdocs/aws-doc-sdk-examples

private static String getBucketPolicyFromFile(String policy_file)
{
  StringBuilder file_text = new StringBuilder();
  try {
    List<String> lines = Files.readAllLines(
    Paths.get(policy_file), Charset.forName("UTF-8"));
    for (String line : lines) {
      file_text.append(line);
    }
  } catch (IOException e) {
    System.out.format("Problem reading file: \"%s\"", policy_file);
    System.out.println(e.getMessage());
  }
  // Verify the policy by trying to load it into a Policy object.
  Policy bucket_policy = null;
  try {
    bucket_policy = Policy.fromJson(file_text.toString());
  } catch (IllegalArgumentException e) {
    System.out.format("Invalid policy text in file: \"%s\"",
        policy_file);
    System.out.println(e.getMessage());
  }
  return bucket_policy.toJson();
}

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

private List<String> getLinesFromCurrentDataFile() throws IOException {
  Path dataFile = Paths.get(TEST_OUT_DIR, fileNameFormat.getCurrentFileName());
  List<String> lines = Files.readAllLines(dataFile, Charset.defaultCharset());
  return lines;
}

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

@Test
public void testLargeGeometryToBingTiles()
    throws Exception
{
  Path filePath = Paths.get(this.getClass().getClassLoader().getResource("large_polygon.txt").getPath());
  List<String> lines = Files.readAllLines(filePath);
  for (String line : lines) {
    String[] parts = line.split("\\|");
    String wkt = parts[0];
    int zoomLevel = Integer.parseInt(parts[1]);
    long tileCount = Long.parseLong(parts[2]);
    assertFunction("cardinality(geometry_to_bing_tiles(ST_GeometryFromText('" + wkt + "'), " + zoomLevel + "))", BIGINT, tileCount);
  }
}

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

public static void main(String[] args) throws Exception {
  Options options = buildOptions();
  CommandLineParser parser = new DefaultParser();
  CommandLine commandLine = parser.parse(options, args);
  if (!commandLine.hasOption(OPTION_SQL_FILE_LONG)) {
    printUsageAndExit(options, OPTION_SQL_FILE_LONG + " is required");
  }
  String filePath = commandLine.getOptionValue(OPTION_SQL_FILE_LONG);
  List<String> stmts = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
  StormSql sql = StormSql.construct();
  @SuppressWarnings("unchecked")
  Map<String, Object> conf = Utils.readStormConfig();
  if (commandLine.hasOption(OPTION_SQL_EXPLAIN_LONG)) {
    sql.explain(stmts);
  } else if (commandLine.hasOption(OPTION_SQL_TOPOLOGY_NAME_LONG)) {
    String topoName = commandLine.getOptionValue(OPTION_SQL_TOPOLOGY_NAME_LONG);
    SubmitOptions submitOptions = new SubmitOptions(TopologyInitialStatus.ACTIVE);
    sql.submit(topoName, stmts, conf, submitOptions, null, null);
  } else {
    printUsageAndExit(options, "Either " + OPTION_SQL_TOPOLOGY_NAME_LONG + " or " + OPTION_SQL_EXPLAIN_LONG +
                  " must be presented");
  }
}

代码示例来源:origin: jooby-project/jooby

List<String> files = Arrays.asList(filename,
   filename.replace(".", File.separator) + ".java");
 List<Path> source = Lists.newArrayList(Paths.get(filename));
 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  @Override
 return new Source(source.get(0), Files.readAllLines(source.get(0), StandardCharsets.UTF_8));
}).orElse(new Source(Paths.get(filename), Collections.emptyList()));

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

static void assertFileContents(final int runNumber) throws IOException {
  final Path path = Paths.get(FOLDER + "/audit.tmp");
  final List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
  int i = 1;
  final int size = lines.size();
  for (final String string : lines) {
    if (string.startsWith(",,")) {
      final Path folder = Paths.get(FOLDER);
      final File[] files = folder.toFile().listFiles();
      Arrays.sort(files);
      System.out.println("Run " + runNumber + ": " + Arrays.toString(files));
      Assert.fail(
          String.format("Run %,d, line %,d of %,d: \"%s\" in %s", runNumber, i++, size, string, lines));
    }
  }
}

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

@Setup
  public void setup()
      throws IOException
  {
    Path filePath = Paths.get(this.getClass().getClassLoader().getResource("large_polygon.txt").getPath());
    List<String> lines = Files.readAllLines(filePath);
    String line = lines.get(0);
    String[] parts = line.split("\\|");
    String wkt = parts[0];
    geometry = GeoFunctions.stGeometryFromText(Slices.utf8Slice(wkt));
    envelope = GeoFunctions.stEnvelope(geometry);
    zoomLevel = Integer.parseInt(parts[1]);
  }
}

相关文章

微信公众号

最新文章

更多