I am a beginner. Reading from text file in Java using a scanner. This code just to read the first 3 tokens isn't working:
try{
Scanner scFile = new Scanner (new File ("readhere.txt")).useDelimiter("#");
String first = scFile.next();
String second = scFile.next();
int third = scFile.nextInt(); // error here. Why cant I store the integer?
}
catch(FileNotFoundException e){
System.out.println("Error");
}
I am trying to read just the first 3 tokens:
Andrew#Smith#21
John#Morris#55
the problem occurs when reading 21. java.util.InputMismatchException
The scanner is including the carriage return character(s) as part of the next readable token which produces an invalid integer. You could do
Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n");
Related
I am a beginner with java and programmin over all, So this the full code for a file reader program that counts words or displays text file content, I wanted to take user inputs for commands that I indicated using an if statement, but String printFileCommand = scan.nextLine(); is not working due to the error addressed below:
package com;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanTwo = new Scanner(System.in);
System.out.println("Please Enter Your File Path");
String filePath = scanTwo.nextLine();
scanTwo.close();
File fileInput = new File(filePath);
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner.nextLine());
fileScanner.close();
System.out.println("Commands: PRINT.FILE --> Prints all file COUNT.WORDS --> Counts all words");
System.out.println("Type Command:");
Scanner scan = new Scanner(System.in);
String printFileCommand = scan.nextLine(); <----ERROR HERE
scan.close();
if (printFileCommand.contains("PRINT.FILE")) {
while (fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
} else if (printFileCommand.contains("COUNT.WORDS")) {
int wordCount = 0;
while (fileScanner.hasNext()) {
String fileWords = fileScanner.next();
wordCount++;
// System.out.println(wordCount);
}
System.out.println(wordCount);
}
else {
System.out.println("COMMAND INVALID!");
}
}
}
```
**Terminal Output:**
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING> c:; cd 'c:\Users\DR\Desktop\FIRST REAL PROGRAMMING'; & 'c:\Users\DR\.vscode\extensions\vscjava.vscode-java-debug-0.30.0\scripts\launcher.bat' 'C:\Program Files\AdoptOpenJDK\jdk-15.0.1.9-hotspot\bin\java.exe' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '-Dfile.encoding=UTF-8' '-cp' 'C:\Users\DR\AppData\Roaming\Code\User\workspaceStorage\458dc35931a3067a355426e5ceeeee32\redhat.java\jdt_ws\FIRST REAL PROGRAMMING_e263b9bc\bin' 'com.FileReader'
Please Enter Your File Path
E://texttwo.txt
This is my text file.
Commands: PRINT.FILE --> Prints all file COUNT.WORDS --> Counts all words
Type Command:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at com.FileReader.main(FileReader.java:21)
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING>
So why is `String printFileCommand = scan.nextLine();` not working? I tried alot, but its not working...
It doesn't work because your stream for System.in is closed.
You can check it for example System.out.println(System.in.available()); and you will see:
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.available(BufferedInputStream.java:410)
you closed it in line: scanTwo.close();
I'm still trying to understand Java myself, but I think you don't exactly need to create and use multiple Scanners to collect data. Since you are searching for strings for the file creations, you could technically do something like:
Scanner scanner = new Scanner(System.in);
String filePath = scanner.nextLine();
With some of the other scanners you can keep since you're specifically calling the fileInputs within the Scanner, but when asking the user for data, I suggest using only one scanner source, but having something like the last line of code I shared as a template for updating your code! If I misunderstood something you're more than welcome to let me know. Thanks!
Please check this question:
NoSuchElementException - class Scanner
Your code will work if you remove the code:
scanTwo.close();
Or removing better:
Scanner scan = new Scanner(System.in);
And use scanTwo for reading (but you don't have to close the scanner with scanTwo.close()).
But I recommend you to read those answers to understand how it works.
How to append text to an existing file in Java?
I am using the method mentioned in the solution and i am taking user input.
But the text is appending with the last word. is there any way to add an new line there?
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
String str= sc.nextLine();
try {
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"), str.getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
You must use the new line character \n in your str variable if you want to move to the next line.
String str = "\n" + sc.nextLine();
You also should put it before the input becouse you will append it at the end of the file.
use the System.lineSeparator() constant that applies at runtime and compatible with all OS.
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"),
(System.lineSeparator() + str).getBytes(),StandardOpenOption.APPEND);
I have a text file:
2|BATH BENCH|19.00
20|ORANGE BELL|1.42
04|BOILER ONION|1.78
I need to get the number of items which is 3 here using JAVA. This is my code:
int Flag=0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
Flag=Flag+1;
}
It is going in an infinite loop.
Can someone please help? Thank you.
You must get the next line to avoid an endless loop.
int Flag = 0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
sc.nextLine();
Flag++;
}
while (sc.hasNextLine()) {
Flag=Flag+1;
String line = sc.nextLine(); //Do whatever with line
}
In the code you have written
int Flag=0;
File file = new File("/Users/a0r01ox/Documents/costl-tablet-automation/src/ItemUPC/ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) { // this line is just checking whether there is next line or not.
Flag=Flag+1;
}
When you write while (sc.hasNextLine()){} it check whether there is nextLine or not.
eg line 1 : abcdefg
line 2: hijklmnop
here your code will just be on line 1 and keep telling you that yes there is a nextLine.
Whereas when you write
while(sc.hasNextLine()){
sc.nextLine();
Flag++;
}
Scanner will read the line 1 and then because of sc.nextLine() it will go to line 2 and then when sc.hasNextLine() is checked it gives false.
Here a user enters a list of 1's and 0's.... so an input would 10001010. However I want it to read from a text file... my text file input.txt also containes 10001010... need the coverDataArray array to be fed the same string from the console as from a file.
I tried Datainput stream however, it throws me the exception
'
Scanner in = new Scanner (System.in);
String data1="";
...
.....
try{
System.out.println("Enter the binary bits");
data1 = in.next();
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}'
You can pass a File Object instead of System.in to Scanner constructor. Try it as shown below:
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String s = "";
while(scanner.hasNextLine()){
s = scanner.nextLine();
// your code. You can also use scanner.next() to read word by word instead of nextLine()
}
Byte.parseByte(data1.substring( i, i+1));
Your exception is caused by the fact that you're going up to length - 1, then length - 1 + 1, which is length, which is goign to cause your ArrayOutOfBoundsException. This can be seen on this line:
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
At one point, i is equal to length-1, or the last index in your String. You then attempt to access the next element, which doesn't exist.
And as for your file, you can pass a File object into the Scanner.
Example
Either..
File file = new File("yourfile.txt");
Scanner s = new Scanner(file);
You are trying to use Byte.parseByte as a methode of parsing binairy input, this doesn't really work as parseByte will try to take a numerical input and parse it into a number between -128 and 127. You should use a different method.
I have a scanner in my program that reads in parts of the file and formats them for HTML. When I am reading my file, I need to know how to make the scanner know that it is at the end of a line and start writing to the next line.
Here is the relevant part of my code, let me know if I left anything out :
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNext() == true)
{
String tempString = sc.next();
if (colorMap.containsKey(tempString) == true)
{
String word = tempString;
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(tempString + " ");
}
}
//closes the files
reader.close();
fWrite.close();
sc.close();
I found out about sc.nextLine(), but I still don't know how to determine when I am at the end of a line.
If you want to use only Scanner, you need to create a temp string instantiate it to nextLine() of the grid of data (so it returns only the line it skipped) and a new Scanner object scanning the temp string. This way you're only using that line and hasNext() won't return a false positive (It isn't really a false positive because that's what it was meant to do, but in your situation it would technically be). You just keep nextLine()ing the first scanner and changing the temp string and the second scanner to scan each new line etc.
Lines are usually delimitted by \n or \r so if you need to check for it you can try doing it that way, though I'm not sure why you'd want to since you are already using nextLine() to read a whole line.
There is Scanner.hasNextLine() if you are worried about hasNext() not working for your specific case (not sure why it wouldn't though).
you can use the method hasNextLine to iterate the file line by line instead of word by word, then split the line by whitespaces and make your operations on the word
here is the same code using hasNextLine and split
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//get the line separator for the current platform
String newLine = System.getProperty("line.separator");
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNextLine())
{
// split the line by whitespaces [ \t\n\x0B\f\r]
String[] words = sc.nextLine().split("\\s");
for(String word : words)
{
if (colorMap.containsKey(word))
{
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(word + " ");
}
}
fWrite.write(newLine);
}
//closes the files
reader.close();
fWrite.close();
sc.close();
Wow I've been using java for 10 years and have never heard of scanner!
It appears to use white space delimiters by default so you can't tell when an end of line occurs.
Looks like you can change the delimiters of the scanner - see the example at Scanner Class:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();