[英]Read from a file until specific sequence of characters
i have a JSON file which looks like this: 我有一个看起来像这样的JSON文件:
{
"id":25,
"type":0,
"date":"Aug 28, 2017 12:14:28 PM",
"isOpen":true,
"message":"test"
}
/*
some lines here, comment, not json
*/
what I would like to do is to be able to read from the file until it detects the beginning of the comment section "/*". 我想做的就是能够从文件中读取,直到它检测到注释部分“ / *”的开头。
I was able to write a bit of code, but the output doesn't seem to be ok for some reasons: 我能够编写一些代码,但是由于某些原因,输出似乎不正确:
BufferedReader br = null;
FileReader fr = null;
String comm = "/*";
fr=new FileReader(FILENAME);
br=new BufferedReader(fr);
String currentLine;
while((currentLine=br.readLine())!=null&&!(currentLine=br.readLine()).equals(comm))
{
System.out.println(sCurrentLine);
}
br.close();
The output only gives me this: 输出只给我这个:
"id": 25,
"date": "Aug 28, 2017 12:14:28 PM",
I dont have the beginning of the json section {
nor the whole json message "isOpen"
, "message"
... 我没有json部分的开头{
也不是整个json消息"isOpen"
, "message"
...
How can i do to read and store the result in a string until the comment section ? 在注释部分之前,我该如何读取结果并将其存储在字符串中?
You are calling twice currentLine = br.readLine()
, therefore reading two lines. 您调用两次currentLine = br.readLine()
,因此读取了两行。 It's the same problem people have when they use 这是人们使用时遇到的同样问题
Scanner sc = new Scanner(System.in);
if (sc.nextLine() != null) // This reads a line
myString = sc.nextLine(); //This reads the next line!
You shouldn't call it the second time -- directly compare your currentLine
with com
. 您不应该第二次调用它-直接将currentLine
与com
比较。
Try: 尝试:
String comm = "/*";
BufferedReader br = new BufferedReader(new FileReader(FILENAME););
StringBuilder sb = new StringBuilder();
String currentLine;
while ((currentLine = br.readLine()) != null && !(currentLine.equals(comm)) {
//System.out.println(currentLine);
sb.append(currentLine);
sb.append("\n");
}
br.close();
System.out.println(sb.toString());
If you want to use a Scanner , it would be something like: 如果要使用Scanner ,它将类似于:
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(FILENAME);
while (sc.hasNext())
sb.append(sc.next());
System.out.println(sb.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.