【问题标题】:How to read txt file and save as a single string in java in order to split it by a certain character [closed]java - 如何读取txt文件并在java中保存为单个字符串以便将其拆分为某个字符[关闭]
【发布时间】:2017-01-30 15:14:39
【问题描述】:

我是 Java 语言的新手,并且找不到:

1. read a txt file
2. save entire txt file as single string
3. once I have the txt file content as a string, break the string (by a certain character such as a new line) into an array of strings that I can work with.

如果您可以包含所需的 import 语句,那对新的 java 程序员也会有帮助。

我正在使用BufferedReader,但我相信这只给了我当前可以使用的线路。

我确实看到BufferedReader 有一个lines() 方法,它返回Stream<String> 的流。

【问题讨论】:

  • 你尝试了什么?你谷歌“Java 读取文件”等吗?
  • 以字符串形式阅读请参阅stackoverflow.com/questions/326390/…
  • 为什么要将其存储为单个字符串?这是一个奇怪的要求。
  • 可以直接在数组中读取文本文件
  • 这可能是家庭作业,您要求我们为您完成。

标签: java string java-8 java-7 text-manipulation


【解决方案1】:

Files#lines 返回文件中所有行的流。您可以将这些行连接成一个字符串,然后根据分隔符将其拆分:

String separator = ":"; // for example...
String entireFile = 
    Files.lines(Paths.get("file.txt")).collect(Collectors.joining());
String[] separated = entireFile.split(separator);

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多