How to detect first and last line during reader.readLine()? - java

I am reading each line of the file in the below way
BufferedReader in = new BufferedReader(new FileReader(inFile));
while (null != (line = in.readLine())) {
}
I want to do some validation in the first line and last line alone. Is there any
way to check if it's a first line and last line inside the while loop
while (null != (line = in.readLine())) {
if(firstlineoffile) {
}
else if (lastlineoffile) {
}
else
{
}
}

Cool question. I played a bit round it and here's an SSCCE, just copy'n'paste'n'run it.
package com.stackoverflow.q2292917;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Test {
public static void main(String... args) throws IOException {
// Create test file.
File file = new File("/test.txt");
PrintWriter writer = new PrintWriter(file);
writer.println("line 1");
writer.println("line 2");
writer.println("line 3");
writer.println("line 4");
writer.println("line 5");
writer.close();
// Read test file.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String next, line = reader.readLine();
for (boolean first = true, last = (line == null); !last; first = false, line = next) {
last = ((next = reader.readLine()) == null);
if (first) {
System.out.println("first line: " + line);
} else if (last) {
System.out.println("last line: " + line);
} else {
System.out.println("normal line: " + line);
}
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
// Delete test file.
file.delete();
}
}
Output:
first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5
I however question the readability and interpretability by starters... ;)

String currentLine = in.readLine();
String nextLine = in.readLine();
boolean hasStarted = false;
while(null != currentLine){
if(!hasStarted){
//first line.
hasStarted = true;
}
//all your processing here.
if(null == nextLine){
//last line, cause there's nothing else coming up
}
currentLine = nextLine;
nextLine = in.readLine();
}

if you add a count, and rearrange your code a little, this should work (I haven't tested this so there may be syntax errros):
int count = 0;
String line = in.readLine();
while (line!=null) {
String currLine = line;
if(count==0){
//currLine is the first line
}
line = in.readLine();
if(line==null){
//currLine is the last line
}
if(count>0 && line!=null){
//do something with lines in between
System.out.println(currLine);
}
count++;
}

public class Vomitfirstline {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("Path"));
br.readLine();
{
while ((sCurrentLine = br.readLine()) != null)
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Someone might well come up with a more elegant solution than this, but here we go:
boolean isFirstLine = true;
do{
String line = in.readLine();
if(isFirstLine){
//this is the first line
isFirstLine = false;
}
else if(line==null){ //previous line was the last line
in.reset();
line = in.readLine();
//do last line specific stuff
break;
}
else {
//do stuff for lines in between
}
in.mark(100);
}while (line!=null);
I haven't tested this, so there might be minor errors. I haven't sorted out exception handling in this code. readLine(), mark() and reset() throw IOException and mark() can also throw IllegalArgumentException

Related

How to fetch a string from a output in console in java and compare it with the expected value

Below is the code:
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The following is my output:
Context successfully set
Script started
LXKADMIN|In/OutBoundValidation|-|50149.11065.26960.11788|inbound=OFF|outbound=OFF
inbound=OFF|outbound=OFF
Script complete
STEP 1: COMPLETED
PASSED: step1
I want to fetch the line 5 "inbound=OFF|outbound=OFF" and check if its value is matching "inbound=OFF|outbound=OFF" then my test case will pass else it will fail.
The TCL Script is:
tcl;
eval {
puts "Script started"
set schemaValidationStr [mql temp query bus LXKADMIN In/OutBoundValidation * select id description dump '|']
puts $schemaValidationStr
set schemaValidation [string range $schemaValidationStr 57 end]
puts $schemaValidation
puts "Script complete"
}
Any suggestion will be really helpful.
If your question is just how to verify that the output returned by your TCL script, contains a specific line, than you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String EXPECTED_LINE_VALUE = "inbound=OFF|outbound=OFF";
public boolean verifyScriptOutput(ChannelExec channel)
throws IOException
{
// Check all lines in output
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String line;
int linenr = 0;
while ((line = reader.readLine()) != null)
{
linenr++;
if (linenr == CHECK_LINE_NR)
return (line.equals(EXPECTED_LINE_VALUE));
}
// If we get here, output has less lines
return (false);
} // verifyScriptOutput
The point at which you are reasoning is not possible because you can not access the console and see what is visualized. Instead you should process the input that the console gets, and outputs it, which is the line variable in your case.
If for you is enough to see that inbound=OFF|outbound=OFF you can search that substring in the line like this:
if(line.indexOf("inbound=OFF|outbound=OFF") != -1) {
// you have a match
}
I'm not sure I understood the question, but you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String CHECK_LINE_VALUE = "inbound=OFF|outbound=OFF";
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int linenr;
boolean line_check_passed;
linenr = 0;
line_check_passed = false;
while ((line = reader.readLine()) != null) {
linenr++;
if (linenr == CHECK_LINE_NR)
line_check_passed = line.equals(CHECK_LINE_VALUE);
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static boolean check(InputStream in, int line, String expected) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int i = 0;
String str;
while ((str = reader.readLine()) != null) {
if (i < line)
i++;
else
return expected.equals(str);
}
return false;
}

Counting number of comments in java

I'm developing a tool to analyse and give some statistics about other people's source code, the tool will be able to recognize many things in the code! Right now am stuck at counting the number of comments on the code, my current code is:
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
To check the code, I am using a test file. But the code is giving me the wrong result in both files, for example; I am getting three in the following file
Yes
//comment
yes
yes
/*
if
random
test
test
*/
While the answer should be two comments!
In the following file, it's showing me that I have five comments while I still actually have two
Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/
The whole approach is flawed. You need to parse the source file properly, at least you need to keep track properly of quotes and nesting of "/*". Note that any comment character combination can appear inside statements like:
System.out.println("// this is *not* a line comment");
String s = "*/ this is not the end of a block comment";
and so on. Then there is the weird behavior with character escape sequences being processed before the file is interpreted:
\u002F* this is a valid comment */
Its not that easy to determine what is a comment and whats not :) I strongly suggest you look for an open source parser solution for java sources.
I think you have a problem in that comments can occur inside or at the end of a line as well...
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.contains("//")) {
count++;
} else if (line.contains("/*")) {
count++;
while (!line.contains("*/") && !(line = br.readLine()).contains("*/"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
Of course the problem here is what if the "//", "/* " or "*/" sequences occur within quoted text....?
I haven't tested your code however, I believe this should work :
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while ((line = br.readLine())!=null && !line.endsWith("'*\'"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
When you meet the /* you should increment the counter and skip the comment section.
Guys here is a easy solution. Just download the cloc software from this link for windows.
This software support every language & can accept folder of files also. Put your folder and cloc in same place and open cmd type this command
cloc-(version no).exe (folder name)
cloc-1.64.exe main
and have the no of lines, blank line and total no of lines in the code.
For more detail see this: http://cloc.sourceforge.net/
enter code here
public class FilterInputStreamDemo {
public static void main(String[] args) {
String line = "";
int comment_count = 0;
int line_count = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
line_count++;
if (line.startsWith("//")) {
comment_count++;
single_comment_count++;
} else if (line.startsWith("/*")) {
comment_count++;
multiple_comment_count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
comment_count++;
multiple_comment_count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("comment_count=" + comment_count);
}
}
package com.usaa.training;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CommentsReading {
public static void main(String[] args) {
String line = "";
int number_of_blocks = 0;
int comment_count = 0;
int line_count = 0;
int TODO = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
File file = new File("C:\\code\\InvolvedPartyBasicInfoMapper.java");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line_count++;
;
if (line.contains("//")) {
if (line.contains("TODO")){
TODO++;
}
comment_count++;
single_comment_count++;
} else if (line.contains("/*") )
{
if (line.contains("TODO")){
TODO++;
}
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
break;
}
while (!(line = br.readLine()).endsWith("'*/'") )
{
line_count++;
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
number_of_blocks++;
break;
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total # of Lines = " + line_count);
System.out.println("Total # of Comment Lines= " +comment_count);
System.out.println("Total # of Single line Comments= " +single_comment_count );
System.out.println("Total # of Comment lines with Block Comments = " +multiple_comment_count );
System.out.println("Total # of Block line Comments = " +number_of_blocks);
System.out.println("No of TODO's = " +TODO);
}
}

Why is the first line of my file not being counted?

I am trying to create a program that counts lines of code, where the commented lines are not included. I have come up with the code below, and its almost working completely, however when gets the strings from the file, it seems to be skipping the first line. Any help would be greatly appreciated!
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
public class locCounter
{
public locCounter(String filename)
{
System.out.println("Counting lines in " + filename + "...");
}
public static void main(String[] args) throws FileNotFoundException
{
boolean isEOF = false;
System.out.println( "What file would you like to count the lines of code for?" );
String programName = "test1.txt";
//System.out.println(programName);
locCounter countLines = new locCounter(programName);
try ( BufferedReader reader = new BufferedReader( new FileReader( programName )))
{
String line = reader.readLine();
int counter = 0;
while ((line = reader.readLine()) != null)
{
line = line.trim();
System.out.println(line);
if (line.startsWith("//"))
{
counter = counter;
}
else
{
counter = counter + 1;
}
}
System.out.println(counter);
reader.close();
}
catch (FileNotFoundException ex)
{
System.out.println("The file was not found in the current directory.");
}
catch (IOException e)
{
System.exit(0);
}
}
}
test1.txt
This file has one line of code
// This comment should not count
This file now has two lines of code
// Another comment that shouldn't be counted
}
A total of 4 lines should be counted.
Output
What file would you like to count the lines of code for?
Counting lines in test1.txt...
// This comment should not count
This file now has two lines of code
// Another comment that shouldn't be counted
}
A total of 4 lines should be counted.
3
Remove this line from your code:
String line = reader.readLine();
It basically reads the line. And later on you have 'while ((line = reader.readLine()) != null)' inside the while condition again, so you read 2 lines in total, but only start processing from second line.
AS #admix has said, your problem is that you should replace this line of code
String line = reader.readLine();
with
String line;
By now, your problem has been solved.
As I can see you use JDK7, so you can write your read file code with fewer lines.
Path path = Paths.get(programName);
try {
try (BufferedReader reader = Files.newBufferedReader(path)){
String line;
while ((line = reader.readLine()) != null) {
//process each line in some way
}
}
} catch (IOException e) {
e.printStackTrace();
}
or even cleaner version
Path path = Paths.get(programName);
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
//process each line in some way
}
} catch (IOException e) {
e.printStackTrace();
}
In addition, your program will be more elegant is you remove those lines, which is unnecessary.
if (line.startsWith("//"))
{
counter = counter;
}

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

Read file and insert data into String[]

public static String[] words = null;
public static String readFile(String name) {
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(name));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
words = everything.split("\\n");//not sure if this is right...
} finally {
br.close();
}
} catch (Exception e) {
e.getMessage();
}
return "Loaded " + i + " words";
}
I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?
The problem is that:
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
sb is never actually appended anything, it is just appending empty strings over and over again.
should be:
while (line != null) {
i++;
sb.append(line);
sb.append("\n");
line = br.readLine();
}

Categories

Resources