Using Java scanner get line number - java

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.

Related

Read from a file until specific sequence of characters

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());

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.

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 to escape a line that starts with a special character while reading files in java

Suppose a file contains the following lines:
#Do
#not
#use
#these
#lines.
Use
these.
My aim is to read only those lines which does not start with #. How this can be optimally done in Java?
Let's assume that you want to accumulate the lines (of course you can do everything with each line).
String filePath = "somePath\\lines.txt";
// Lines accumulator.
ArrayList<String> filteredLines = new ArrayList<String>();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = bufferedReader.readLine()) != null) {
// Line filtering. Please note that empty lines
// will match this criteria!
if (!line.startsWith("#")) {
filteredLines.add(line);
}
}
}
finally {
if (bufferedReader != null)
bufferedReader.close();
}
Using Java 7 try-with-resources statement:
String filePath = "somePath\\lines.txt";
ArrayList<String> filteredLines = new ArrayList<String>();
try (Reader reader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (!line.startsWith("#"))
filteredLines.add(line);
}
}
Use the String.startsWith() method. in your case you would use
if(!myString.startsWith("#"))
{
//some code here
}
BufferedReader.readLine() return a String. you could check if that line starts with # using string.startsWith()
FileReader reader = new FileReader("file1.txt");
BufferedReader br = new BufferedReader(reader);
String line="";
while((line=br.readLine())!=null){
if(!line.startsWith("#")){
System.out.println(line);
}
}
}

Java read in single file and write out multiple files

I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}

Categories