【发布时间】:2019-06-27 12:19:50
【问题描述】:
我正在解析 txt 文件并执行一些编辑任务。我在将多行字符串更改为一行字符串时卡住了。
工作流程: 1)将多行合并为一行 2)提取包含一些字符或startsWith的特定行
已经尝试了一些方法,但没有想要的结果。
目标是拥有这一行:
Jrn.Directive "WindowSize" , "[A.rvt]", "Floor Plan: Level 1" , 1912, 849
基于
Jrn.Directive "WindowSize" _
, "[A.rvt]", "Floor Plan: Level 1" _
, 1912, 849
试过了:
line.lines().collect(Collectors.joining("_"+"[\n]"));
或
line.replaceAll(" _\n" +
" ,");
感谢您的任何建议 更新:
工作流程:
-
文本包含以下文本(它是整个 txt 文件的一小部分) - 我无法将其粘贴为代码,请看截图
Jrn.Directive "WindowSize" _ ,“[A.rvt]”,“平面图:1 级”_ , 1912, 849 ' 0:
请看截图https://i.ibb.co/0cRrwcR/2019-02-03-1947.png
-
因为我将提取以 Jrn.D 开头的字符串等我需要 加入这个并获得
Jrn.Directive "WindowSize" , "[A.rvt]", "平面图: Level 1" , 1912, 849
我认为有必要首先定义需要连接的行,然后我可以提取包含有趣信息的行,例如这些以 Jrn.D 开头的行。
编写我用来查找特定刺痛的代码
import java.io.*;
import java.util.stream.Collectors;
public class ReadFromFile {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "test.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
// Im defining which lines are important for me but firstly I
//need have them in one line especially when looking for Jrn
if (line.startsWith("Jrn")||
line.contains("started recording journal file")||
line.contains("' Build:")|| line.contains("Dim Jrn"))
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
【问题讨论】:
-
“提取包含某些字符或startsWith的特定行”到底是什么意思,因为从我认为的意思来看,您可能想要反转该工作流程?
-
@Garikai 我发布了 img 和其他信息。我希望现在我的意思可以理解了,
-
发现了类似的东西——同样的问题——如何实现stackoverflow.com/questions/5516020/…
-
好的,但是“
Jrn.Directives”之间的所有内容都没有被序列化成一行? -
是的,只需要加入Jrn.Directives这一行和下面两行,剩下的就可以了。我想知道如何解决它而不是必要时我会将此解决方案应用于其他情况
标签: java string text-files bufferedreader