findInLine error only searches the first line - java

Here's the code:
BufferedReader in= new BufferedReader(new FileReader("C:\\Users\\ASUS\\Desktop\\123.txt"));
Scanner scanner= new Scanner(in);
while((scanner.findInLine("abc"))!=null){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
}
findInLine only searches the first line not the others. So it prints nothing.
How can i fix this problem?

You should be looping over all the lines - and then if the line matches, then print it out (or whatever). For example:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Now check the line, and do whatever you need.
}
Or you could still use findInLine, just explicitly calling nextLine as well:
while (scanner.hasNextLine()) {
if (scanner.findInLine(...)) {
...
}
// Read to the end of the line whether we found something or not
scanner.nextLine();
}

Related

How to print a full line of text in java (from input file)

I'm trying to print each individual line of an external file, but I can only manage to print each individual word. Here's what my code currently looks like:
Scanner scnr = new Scanner(System.in);
System.out.println("Enter input filename: ");
String inputFile = scnr.next();
FileInputStream fileByteStream = null;
Scanner inFS = null;
fileByteStream = new FileInputStream(inputFile);
inFS = new Scanner(fileByteStream);
while (inFS.hasNext()) {
String resultToPrint = inFS.next();
System.out.println(resultToPrint);
}
So, for example, if the external .txt file is something like this:
THIS IS THE FIRST LINE.
(new line) THIS IS THE SECOND LINE.
(new line) THIS IS THE THIRD LINE.
...
Then right now it prints like this:
THIS
(new line) IS
(new line) THE
(new line) FIRST
(new line) LINE
(new line) THIS
(new line) IS
...
and I want it to print like how it appears in the original file.
Any suggestions on how to make each iteration of resultToPrint be a full line of text, as opposed to a single word? (I'm new to java, so sorry if the answer seems obvious!)
Replace the line
inFS = new Scanner(fileByteStream);
by
inFS = new Scanner(fileByteStream).useDelimiter( "\\n" );
This will set the "word" separator to the line feed character, making the full line a single "word".
Or use java.nio.files.Files.lines() …
Also java.io.BufferedReader.lines() would be a nice alternative …
In order to read a file you need a BufferedReader:
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
Then use it's method readLine:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
This code reads every line of a file then prints it:
try (BufferedReader br = new BufferedReader(new FileReader(new File(filePath)))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
Simpler and cleaner approach would be:
FileInputStream fis = new FileInputStream("filename");
Scanner sc = new Scanner(fis);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
or
BufferedReader br = new BufferedReader(new FileReader("filename"));
br.lines().forEach(System.out::println);

How to return inside a while loop?

I want to have a method that returns the value that is presentend in the while loop. My code represents the reading of a txt file, where I read line by line and my goal is to return everytime it founds a line but is is showing me the same number over and over.
public String getInputsTxtFromConsole() {
String line = "";
//read inputs file
try {
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
}
} catch (FileNotFoundException e) {
}
return "";
}
As Nick A has said the use of return has, in this context two uses: return the value of a function and exit the function. I you need all the values as the are generated you can, for example,
Call a method that consume the new value:
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
ConsumerMethod(line);
}
Store in a global var like ArrayList, String[],...
Print it System.out.println(line).
...
But you cannot return a value and expect that the function continues working.
As I mentioned, pass the same scanner as a parameter to a method that reads a line and returns the line. You may want to define how it responds once there are no remaining lines.
public String getInputsTxtFromConsole(Scanner scanner) {
try {
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
} catch (FileNotFoundException e) {
}
return null;
}
I would also recommend using a different class to read from a file. BufferedReader would be a better approach.
BufferedReader in = new BufferedReader(new FileReader (file));
... // in your method
return in.readLine(); //return null if the end of the stream has been reached

Java Scanner Split Strings by Sentences

I am trying to split a paragraph of text into separate sentences based on punctuation marks i.e. [.?!] However, the scanner splits the lines at the end of each new line as well, even though I've specified a particular pattern. How do I resolve this? Thanks!
this is a text file. yes the
deliminator works
no it does not. why not?
Scanner scanner = new Scanner(fileInputStream);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
line = scanner.next();
System.out.println(line);
}
I don't believe the scanner splits it on line breaks, it is just your "line" variables have line breaks in them and that is why you get that output. For example, you can replace those line breaks with spaces:
(I am reading the same input text you supplied from a file, so it has some extra file reading code, but you'll get the picture.)
try {
File file = new File("assets/test.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
String sentence = scanner.next();
sentence = sentence.replaceAll("\\r?\\n", " ");
// uncomment for nicer output
//line = line.trim();
System.out.println(sentence);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This is the result:
this is a text file
yes the deliminator works no it does not
why not
And if I uncomment the trim line, it's a bit nicer:
this is a text file
yes the deliminator works no it does not
why not

Scanner nextline() only printing new lines

I'm trying to use scanner to print lines from a text file, but it only prints first line before printing only new lines until while loop goes through file.
String line;
File input = new File("text.txt");
Scanner scan = new Scanner(input);
while (scan.hasNext()) //also does not work with hasNextLine(), but additional error
{
line = scan.nextLine();
System.out.println(line);
//other code can see what is in the string line, but output from System.out.println(line); is just a new line
}
How can I get System.out.println() to work with this code?
This is the Javadoc for nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
You want next() instead:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Your code becomes:
while (scan.hasNext())
{
line = scan.next();
System.out.println(line);
}
You may use .next() method:
String line;
File input = new File("text.txt");
Scanner scan = new Scanner(input);
while (scan.hasNext()) //also does not work with hasNextLine(), but additional error
{
line = scan.next();
System.out.println(line);
}

Read one line from input file per iteration

Task: read a line from an input file. If the first word of the line is PRINT, then print the contents of the rest of the line.
Code:
else if(Data.compareTo("PRINT") == 0){
while(inFile.hasNext()){
Data = inFile.next();
System.out.print( Data + " ");
}
}
Question: How to code the scanner so that the scanner only reads one line of information at a time?
public static void ReadAndProcessPrint(File fileToRead) throws FileNotFoundException {
java.util.Scanner scanner = new Scanner(fileToRead);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.startsWith("PRINT")){
String restOfLine = line.substring(5);
System.out.println(restOfLine);
}else{
//do other things
}
}
}
Hint: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
Create a InputStreamReader and using it create a BufferedReader, use readLine method.

Categories

Resources