Read one line from input file per iteration - java

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.

Related

Is there a way for Java Scanner to include '\n' when it is reading lines?

Is there any way for java.util.Scanner to include the newline escape character when reading from a file?
This is my code:
File myFile = new File("file.txt");
Scanner myReader = new Scanner(myFile);
String content = "";
while(myReader.hasNextLine()) {
content += myReader.nextLine();
}
System.out.println(content);
myReader.close();
When it reads from the file, it doesn't include '\n' or any new lines. Does anyone know how to do this?
Thanks
When it reads from the file, it doesn't include '\n' or any new lines.
Does anyone know how to do this?
You can add the new line explicitly as follows:
while(myReader.hasNextLine()) {
content += myReader.nextLine() + "\n";
}
I also recommend you use StringBuilder instead of String for appending in a loop.
StringBuilder content = new StringBuilder();
while (myReader.hasNextLine()) {
content.append(myReader.nextLine()).append(System.lineSeparator());
// or the following
// content.append(myReader.nextLine()).append('\n');
}
Check StringBuilder vs String concatenation in toString() in Java to learn more about it.
If you you just want to read in lines and the line terminator you can do it by changing the behavior of Scanner.next(). If you run the following it will take in the line and the new line terminator as one unit.
\\z is a regex directive that says to include the line terminator.
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z");
for (int i = 0; i < 5; i++) {
String line = scan.next();
System.out.println(line + "on next line");
}
To read from a file, try this.
try {
Scanner scan = new Scanner(new File("f:/Datafile.txt"));
scan.useDelimiter("\\z");
while (scan.hasNextLine()) {
String line = scan.next();
System.out.print(line);
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

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

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

How to skip reading a line with scanner

I have read in a text file and am scanning said file. The question I have is how would I skip over lines that include a certain character (in my case lines that start with " // " and " " (whitespace).
Here is my code at the moment. Can someone point me in the right direction?
File dataFile = new File(filename);
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine();
if (lineOfText.startsWith("//")) {
System.out.println(); // not sure what to put here
}
System.out.println(lineOfText);
}
scanner.close();
You will only want to execute the code within the while-loop if the line of text doesn't start with a / or whitespace. You can filter these out as seen below:
while(scanner.hasNext()) {
String lineOfText = scanner.nextLine();
if (lineOfText.startsWith("//") || lineOfText.startsWith(" ")) {
continue; //Exit this iteration if line starts with space or /
}
System.out.println(lineOfText);
}
As you are iterating over the lines of text in the file, use String's startsWith() method to check if the line starts with the sequences you are trying to avoid.
If it does, continue to the next line. Otherwise, print it.
while (scanner.hasNext()) {
String lineOfText = scanner.nextLine();
if (lineOfText.startsWith("//") || lineOfText.startsWith(" ") ) {
continue;
}
System.out.println(lineOfText);
}
Just use a continue like -
if (lineOfText.startsWith("//")) {
continue; //would skip the loop to next iteration from here
}
Detials - What is the "continue" keyword and how does it work in Java?
If you're just interested in printing out the lines of code that begin with a "//" then you should just use the continue keyword in java.
String lineOfText = scanner.nextLine();
if (lineOfText.startsWith("//")) {
continue;
}
See this post for more information regarding the "continue" keyword.
You can just insert "else" in your code like:
public static void main(String[] args) throws FileNotFoundException {
File dataFile = new File("testfile.txt");
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine();
if (lineOfText.startsWith("//")) {
System.out.println();
}
else
System.out.println(lineOfText);
}
scanner.close();
}
}

Java - How to read a big file word by word instead of line by line?

I'd like to read the "text8" corpus in Java and reformat some words. The problem is, in this 100MB corpus all words are on one line. So if I try to load it with BufferedReader and readLine, it takes away too much space at once and can't handle it to separate all the words in one list/array.
So my question: Is it possible in Java to read instead of line by line a corpus, to read it word by word? So for example because all words are on one line, to read for example 100 words per iteration?
you can try using Scanner and set the delimiter to whatever suits you:
Scanner input=new Scanner(myFile);
input.useDelimiter(" +"); //delimitor is one or more spaces
while(input.hasNext()){
System.out.println(input.next());
}
I would suggest you to use the "Character stream" with FileReader
Here is the example code from http://www.tutorialspoint.com/java/java_files_io.htm
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
It reads 16 bit Unicode characters. This way it doesnt matter if your text is in one whole line.
Since you're trying to search word by word, you can easy read till you stumble upon a space and there's your word.
Use the next method of java.util.Scanner
The next method 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 Scanner.hasNext returned true.
Example:
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String a = sc.next();
String b = sc.next();
System.out.println("First Word: "+a);
System.out.println("Second Word: "+b);
sc.close();
}
Input :
Hello Stackoverflow
Output :
First Word: Hello
Second Word: Stackoverflow
In your case use Scanner for reading the file and then use scannerobject.next() method for reading each token(word)
try(FileInputStream fis = new FileInputStream("Example.docx")) {
ZipSecureFile.setMinInflateRatio(0.009);
XWPFDocument file = new XWPFDocument(OPCPackage.open(fis));
ext = new XWPFWordExtractor(file);
Scanner scanner = new Scanner(ext.getText());
while(scanner.hasNextLine()) {
String[] value = scanner.nextLine().split(" ");
for(String v:value) {
System.out.println(v);
}
}
}catch(Exception e) {
System.out.println(e);
}

Categories

Resources