Read from a file until specific sequence of characters - java

i have a JSON file which looks like this:
{
"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"...
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. 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.
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:
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(FILENAME);
while (sc.hasNext())
sb.append(sc.next());
System.out.println(sb.toString());

Related

Java - Only read first line of a file

I only want to read the first line of a text file and put that first line in a string array.
This is what I have but its reading the whole file.
ex text in myTextFile:
Header1,Header2,Header3,Header4,Header5
1,2,3,4,5
6,7,8,9,10
String line= System.getProperty("line.separator");
String strArray[] = new String[5];
String text = null;
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
while (text != line) {
System.out.println("text = " + text );
strArray= text.split(",");
}
use BufferedReader.readLine() to get the first line.
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
System.out.println("Firstline is : " + text);
If I understand you, then
String text = brTest.readLine();
// Stop. text is the first line.
System.out.println(text);
String[] strArray = text.split(",");
System.out.println(Arrays.toString(strArray));
With Java 8 and java.nio you can also do the following:
String myTextFile = "path/to/your/file.txt";
Path myPath = Paths.get(myTextFile);
String[] strArray = Files.lines(myPath)
.map(s -> s.split(","))
.findFirst()
.get();
If TAsks assumption is correct, you can realize that with an additional
.filter(s -> !s.equals(""))
Also, beside of all other solutions presented here, you could use guava utility class (Files), like below:
import com.google.common.io.Files;
//...
String firstLine = Files.asCharSource(myTextFile).readFirstLine();
I think you are trying to get one line only if it's not empty.
You can use
while ((text=brTest .readLine())!=null){
if(!text.equals("")){//Ommit Empty lines
System.out.println("text = " + text );
strArray= text.split(",");
System.out.println(Arrays.toString(strArray));
break;
}
}
Use this
BuffereedReader reader = new BufferedReader(new FileReader(textFile));
StringBuilder builder = new StringBuilder();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
break;
}
if(sb.toString.trim().length!=0)
System.out.println("first line"+sb.toString);
I hope this will help someone
to read the first line:
public static String getFirstLine() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = br.readLine();
br.close();
return line;
}
to read the whole text:
public static String getText() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line).append("\n");
line = br.readLine();
}
String fileAsString = sb.toString();
br.close();
return fileAsString;
}
You need to change the condition of your loop
String[] nextLine;
while((nextLine = brTest.readLine()) != null) {
...
}
ReadLine reads each line from beginning up to the occurrence of \r andor \n
You can also use tokenizer to split the string
String[] test = "this is a test".split("\\s");
In addition it seems the file is of type CSV if it is please mention that in the question.

Using Java scanner get line number

I'm using the code below to compare two file input streams and compare them:
java.util.Scanner scInput1 = new java.util.Scanner(InputStream1);
java.util.Scanner scInput2 = new java.util.Scanner(InputStream2);
while (scInput1 .hasNext() && scInput2.hasNext())
{
// do some stuff
// output line number of InputStream1
}
scInput1.close();
scInput2.close();
How can I output the line number inside the while loop?
Use LineNumberReader on an InputStreamReader. As it is precisely made for that sole purpose.
try (LineNumberReader scInput1 = new LineNumberReader(new InputStreamReader(
inputStream1, StandardCharsets.UTF_8));
LineNumberReader scInput2 = new LineNumberReader(new InputStreamReader(
inputStream2, StandardCharsets.UTF_8))) {
String line1 = scInput1.readLine();
String lien2 = scInput2.readLine();
while (line1 != null && line2 != null) {
...
scInput1.getLineNumber();
line1 = scInput1.readLine();
line2 = scInput2.readLine();
}
}
Here I have added the optional CharSet parameter.
A Scanner has additional tokenizing capabilities not needed.

How to read data from System.in to solve the task?

I'm working on this item. I did the spell checking algorithm but I have no idea how to read data correctly. When I use this:
StringBuilder text = new StringBuilder();
Scanner sc = new Scanner(System.in);
String temp;
while ((temp = sc.nextLine()).length() > 0){
text.append(temp);
}
/*spell checking algorithm*/
It waits for the empty string.
In this case:
while (sc.hasNext()){
text.append(temp);
}
it doesn't continue to execute the code at all. If I try to read 10000 signs I should type it all.
How could I read data correctly for this task?
Read them from file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
//do what you want
}

How can I overwrite lines from text file to specific lines in another file instead of appending them

public class AddSingleInstance {
public void addinstances(String txtpath,String arffpath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\src\\text.txt"));
FileWriter fw = new FileWriter("C:\\src\\" + test.txt,true);
StringBuilder sb = new StringBuilder();
//String toWrite = "";
String line = null;
while ((line = reader.readLine())!= null){
// toWrite += line;
sb.append(line);
sb.append("\n");
}
reader.close();
fw.write(sb.toString());
fw.flush();
fw.close();
}
}
my code is working on append lines from text file(A) to specific lines in another file(B), like
I
AM
......
(above lines are fixed, cannot be overwriting)
student(New string was added from text file)
now(New string...)
How can I overwrite those lines into file(B) instead of appending them on B?
You can use java.io.RandomAccessFile to access file(B) and write to it at the desired location.

How to convert xml file to string without escaping XML using java

I've a XML file and want to send its content to caller as string. This is what I'm using:
return FileUtils.readFileToString(xmlFile);
but this (or that matter all other ways I tried like reading line by line) escapes XML elements and enclose whole XML with <string> like this
<string>>&lt;.....</string>
but I want to return
<a>....</a>
I'd advise using a different file reader maybe something like this.
private String readFile( String file ) throws IOException {
BufferedReader reader = new BufferedReader( new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
}
It's probably a feature of file utils.
According to your question you just want to read the file. You can use FileReader and BufferedReader to read the file.
File f=new File("demo.xml");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!=null)
{
System.out.println(line);
}
Hope this answer helps you
IOUtils works well. It's in package org.apache.commons.io. The toString method takes an InputStream as a parameter and returns the contents as a string maintaining format.
InputStream is = getClass.getResourceAsStream("foo.xml");
String str = IOUtils.toString(is);
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!= null){
sb.append(line.trim());
}

Categories