简体   繁体   English

在输入文件上使用String.split

[英]Using String.split on input file

So I have an input file of the form: 所以我有一个形式的输入文件:

AdjGraphHeader
11
20
30
.
.
.

and I need to create a string array that holds each line separately. 并且我需要创建一个字符串数组来单独保存每一行。 So I read the file using: 所以我使用以下命令读取文件:

String s = FileUtils.readFileToString(f);
Words w = new Words(s, (long)s.length());

and then the words constructor did the following: 然后单词构造函数执行以下操作:

public Words(String str, long n_) {
    strings = str.split("\\n");
    string = str;
    n = n_;
    m = strings.length;
}

The issue seems to be that there is an extra line at the end of adjGraphHeader , but I have no idea how to get rid of it. 问题似乎是adjGraphHeader的末尾有多余的一行,但是我不知道如何摆脱它。 Any help would be greatly appreciated. 任何帮助将不胜感激。

I suspect that your lines are separated not by \\n but by \\r\\n so if you remove \\n you still have \\r after each word and while printing it you will see empty line. 我怀疑您的行不是由\\n隔开,而是由\\r\\n隔开,因此,如果删除\\n ,则每个单词后仍会有\\r ,并且在打印时会看到空行。 One of solutions could be splitting using this regular expression 解决方案之一可以使用此正则表达式进行拆分

"\\r?\\n|\\r" - ? "\\r?\\n|\\r" - ? makes element described before it optional, | 使前面描述的元素为可选, | represent "or" operator 代表“或”运算符

which will handle line separators if forms \\r \\r\\n \\n . 如果格式为\\r \\r\\n \\n ,它将处理行分隔符。

You can also use something IMHO simpler like 您还可以使用恕我直言的简单方法

List<String> lines = Files.readAllLines(Paths.get("locationOfFile"));

or if you already have File f 或者如果您已经拥有File f

List<String> lines = Files.readAllLines(f.toPath());

and store each line in list (you can later convert this list to array if you really need it) 并将每行存储在列表中(如果您确实需要此列表,可以稍后将其转换为数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM