使用 BufferedReader:我有一个文本文件,其中包含如下所列的类似行。 文本文件行示例:
ABC DEF EFG 1.2.3.3 MGM -Ba\
10.101.0.10
如何删除 -Ba
之后的行字符 \
并将下一行/字段连接到第一行以获得新行然后存储它放在一个数组中以便稍后打印。
我想要的是如果在第一行末尾找到\
,则能够连接两行,然后分配“两行”(现在是一行)的每个元素由分隔符“”分隔到我可以稍后调用进行打印的字段。但我还想删除在行末尾找到的不需要的字符 \
。
这是我想要存储在数组中的新组合行
Field-1 Field-2 Field-3 Field-4 Field-5 Field-6;
新数组的第一行等于
Field-1 = ABC Field-2 = DEF Field-3 = EFG Field-4 = 1.2.3.3 Field-5 = -Ba Field-6 = 10.101.0.10;
如果在第一行末尾找到 \
char,将生成新的组合行(2 in one)。
到目前为止我在 Bufferedreader 类中所拥有的内容
public class ReadFile {
private String path;
ReadFile(String filePath) {
path = filePath;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
//Not sure if It's better to have while loop instead of this to reach end of file, let me know what you think?
int readLines() throws IOException {
FileReader f2r = new FileReader(path);
BufferedReader bf = new BufferedReader(f2r);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
最佳答案
这将读取一个文本文件并将以“\”结尾的任何行与以下行连接起来。
这里有两个重要的注意事项,假设输入正确并且\字符是该行中的最后一个字符(如果这不是真的,则必须清理输入),并且文件的最后一行不以反斜杠结尾。
try (Bufferedreader br = new BufferedReader(new FileReader(file))) {
String line;
StringBuilder concatenatedLine = new StringBuilder();
List<String> formattedStrings = new ArrayList<String>();
while((line = br.readLine()) != null){
//If this one needs to be concatenated with the next,
if( line.charAt(line.length() -1) == '\\' ){
//strip the last character from the string
line = line.substring(0, line.length()-1);
//and add it to the StringBuilder
concatenatedLine.append(line);
}
//If it doesn't, this is the end of this concatenated line
else{
concatenatedLine.append(line);
//Add it to the formattedStrings collection.
formattedStrings.add(concatenatedLine.toString());
//Clear the StringBuilder
concatenatedLine.setLength(0);
}
}
//The formattedStrings arrayList contains all of the strings formatted for use.
}
关于java - BufferedReader 和 Stream Line Java 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31319203/