我想读取一个文件,读取成功,但是由于我读取的文件包含多行,所以接收到的字符串中包含“\n”。我怎样才能以优雅的方式处理这个问题?我不想在之后替换它,有没有更优化的方法来读取文件?
输入.txt
Anne big word random etc
another line here still input text
我的Java代码:
private static String readLineByLineJava8(String filePath)
{
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8))
{
stream.forEach(s -> contentBuilder.append(s).append("\n"));
}
catch (IOException e)
{
e.printStackTrace();
}
return contentBuilder.toString();
}
private void ReadStringPrintOccurence() {
String filePath = "imput.txt";
String temp = readLineByLineJava8(filePath);
String[] array = temp.split("\\r?\\n"); \\split in two arrays
array = temp.split(" "); \\ further split by space
}
我尝试通过首先按行分隔符拆分数组,然后按它们之间留下的空格来拆分数组,以获取字符串数组中的单词来解决此问题。通过这样做我得到 array[4] = etc\nanother and array[9] = text\n
。
您对此有何建议?
最佳答案
如果我理解正确,您需要读取保留换行符的文件..并最终将它们收集在字符串中。 我最近在文件中使用不同的 Api 做了同样的事情。这是代码。
private static String readFileAsString(String filename) throws URISyntaxException, IOException {
return new String(Files.readAllBytes(Paths.get(filePath)));
}
您可以在这篇文章中获得更多详细信息 - https://www.mkyong.com/java/java-files-readallbytes-example/
关于java - 从文件读取字符串并将其存储在本地,如何从文本中删除行分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412099/