Read an instruction line by line java - java

I have a set of instructions in a text file:
LoadA 0
LoadB 1
Add
Store 0
LoadA 2
etc...
I know I can use Scanner and hasNextLine but not sure how to implement this and have the instructions read and understood.

As much as the people above would like you to do this on your own I will answer this question because I remember how difficult it was to learn. As long as you learn from the and don't just copy them this should be useful.
Scanner sc = new Scanner(System.in); //read from the System.in
while (sc.hasNextLine()) { //this will continue to itterate until it runs out
String[] x = sc.nextLine().split(" ");
//this takes your input and puts it into a string array where there is a
//space e.g. ["LoadA", "0"]
}
I hope this helps. You are still required to solve the problem. You now have the ability to get the content now. Good luck.

Scanner inFile = null;
try
{
// Create a scanner to read the file, file name is parameter
inFile = new Scanner (new File("whatever.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!");
// Stop program if no file found
System.exit (0);
}
then,
while(inFile.hasNextLine()){
(some variable) = inFile.nextLine();
(do something to that variable);
}
if this doesn't solve the question, I would recommend taking a look at http://www.cs.swarthmore.edu/~newhall/unixhelp/Java_files.html

Related

Java Scanner Error : java.util.NoSuchElementException: No line found -- java.base/java.util.Scanner.nextLine(Scanner.java:1651))

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 use Constructor Scanner in java programming to grasp number of lines in text file

I was trying to remove the first line in text file using java code referencing from this link but still the scanner does not contain any text, so it write nothing in the text file, please help, what is then problem...?
here is a peace of code,
File path=new File("C:/Users/kassim Ismail/workspace/Coding/textdoc.txt");
Scanner scan=new Scanner(path);
FileWriter newread=new FileWriter("C:\\Users\\kassim Ismail\\workspace\\Coding\\textdoc.txt");
BufferedWriter newreader=new BufferedWriter(newread);
while(scan.hasNextLine()){
String nextline=scan.nextLine();
if(nextline.equals("\n")){
newreader.newLine();
}else{
newreader.write(nextline);
}
}
scan.close();
newreader.close();
newread.close();
}
Right now I don't see any mistake in your code (reader/writer should work). One thing I am unsure about is wether the blank space in your Filepath is problematic or not (Some programs can't work with blank spaces in file paths I am not sure about Java though).
Maybe you could add some System.out.println("") statements for debugging purposes. For Example (testing if the input file exists):
System.out.println("Inputfile exists: "+path.exists())
printing the read line:
System.out.println("Read line: "+nextline)
private boolean removeTopLine(File file){
try{
boolean status = false;
Scanner s = new Scanner(file);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String content = "";
int counter = 0;
while (s.hasNextLine()){
if (counter > 0){
content += s.nextLine();
}
counter++;
}
writer.write(content);
writer.close();
status = true;
}
catch (Exception e){
e.printStackTrace();
}
return status;
}
This is a functional code snippet that would delete the first line of a file however there could be debate on efficiency.

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?

Is there a way for me to be able to use the same scanner for both a System.in Input and for a FileInputStream Input?
Here is how I have initialized the scanner in my main class:
public class Nimsys {
public static Scanner keyboardIn;
static {
keyboardIn = new Scanner(System.in);
} ...
In the main class Nimsys here is how I get input:
String inputString1 = keyboardIn.nextLine();
In another class here is how I use the scanner from Nimsys:
int inputInt1 = Nimsys.keyboardIn.nextInt();
But now in my main class Nimsys I am trying to scan in a whole file - so far I have used another scanner, as you can see in the code below. However, is it possible to have it all done by the original scanner?
try
{
inputStream = new Scanner(new FileInputStream("file.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File morestuff.txt was not found");
}
String[] reopenPlayers = new String[100];
int i = 0;
while(inputStream.hasNextLine()){
reopenPlayers[i]=inputStream.nextLine();
System.out.println(reopenPlayers[i]);
}
Thanks a lot!
Tom
If I understand your question (not that I think a global variable is a great solution), you could change (and perhaps rename)
keyboardIn = new Scanner(System.in);
to something like
try {
keyboardIn = new Scanner(new FileInputStream("file.txt"));
} catch (FileNotFoundException e) {
System.out.println("file \"file.txt\" not found");
e.printStackTrace();
}
and then remove the try-catch from
inputStream = new Scanner(new FileInputStream("file.txt"));
and modify it to something like
inputStream = Nimsys.keyboardIn;
(or replace inputStream with Nimsys.keyboardIn and not to be prescriptive but perhaps rename Nimsys.keyboardIn to Nimsys.in). Hopefully you're using an IDE that supports refactoring.
No you cannot do that, Scanner is just a wrapper class, which means the actual stream sources you are using are FileInputStream and system.in, obviously you cannot do this, and there is not much benefit if you can do this.
I would recommend against you trying to use the same scanner for multiple sources. From what I can tell from the code you've described, you wouldn't gain anything by it. In general, one Scanner should represent a single source of data.
However, if you're dead-set on the idea, you can write your own implementation of InputStream which combines the input from System.in and your FileInputStream. For ideas on how to do this, see this related question. Then construct the scanner with an instance of your two-source InputStream.
This brings up a host of other questions though- how exactly do you intend to properly combine the input from the two sources? The file contents will be available as soon as the file has been opened. The input from System.in will be available as the user types it. How should your combined Scanner choose what to output and when? These are questions you would have to answer if you choose to write your own InputStream to wrap the two sources.

Read data from file into an array Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:
Inside the TestSubject class -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
Inside the subject class -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
I then want to read this file and pass the data through to an arraylist. The file might look something like:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
Even if there is a good tutorial around that I might be able to be pointed in the right direction...
Thanks for editing your post. Much easier to help when I can see what's causing problems.
You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.
You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.
The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.
Give "Reading a plain text file in Java" a read.
Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:
public static void main(String[] args){
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//Path leading to the text file
Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");
int count = 0;//Will indicate which list to add the current line to
//Create a buffered reader to read in the lines of the file
try(BufferedReader reader = new BufferedReader(new FileReader(data.toFile()))){
String line = "";
while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
count++;//Increment number changing from odd to even or vice versa
if(count % 2 == 0){//If number is even then add to subject codes
subjectCodes.add(line);
} else {//Otherwise add to subject names
subjectNames.add(line);
}
}
} catch (IOException io){
System.out.println("IO Error: " + io.getMessage());
}
System.out.println("Codes: ");
display(subjectCodes);
System.out.println("\nNames: ");
display(subjectNames);
}
private static void display(Collection<String> c){
for(String s :c){
System.out.println(s);
}
Hope it helps!

File I/O Java prompt

I had a quick questions about prompting and accepting a file name, then making the file-text a scanner object.
I want the program to prompt the user to enter the name of a file, until he gets one which exists, then for the file-text to be used as a scanner object.
This is the code I have so far, it works to the point where I exit the while {} loop, but then when I try and process the scanner item like while (input.hasNextLine()) { it gives me an error saying it can't find the scanner item.
It's probably a silly mistake, but I just cannot seem to get it.
The whole code is below:
import java.io.*;
import java.util.*;
public class PersonalityTest {
public static void main(String[] args) throws FileNotFoundException {
boolean isFile = false;
Scanner sc = new Scanner(System.in);
System.out.print("Input file name? ");
String fileName = sc.next();
File inputFile = new File(fileName);
while (isFile == false) {
if (inputFile.exists()) {
Scanner input = new Scanner(inputFile);
isFile = true;
}
}
while(input.hasNextLine()) {
}
}
The scope of the input variable is local to the while (isFile == false) block. Declare it outside otherwise it won't be visible.
For the first part "I want the program to prompt the user to enter the name of a file, until he gets one which exists": Move this code:
Scanner sc = new Scanner(System.in);
System.out.print("Input file name? ");
String fileName = sc.next();
File inputFile = new File(fileName);
into a method and call it inside the while (isFile == false) block before the exists check (the method should return with the file or make the variable visible in the block by some other means).
You can't access input outside the if statement, sice the compiler is not sure, it will pass the test, you can do this:
Scanner sc = new Scanner(System.in);
Scanner input = null;
boolean isFile = false;
while (isFile == false){
System.out.print("Input file name? ");
String fileName = sc.next();
File inputFile = new File(fileName);
if (inputFile.exists()){
input = new Scanner(inputFile);
isFile = true;
}
}
But will throw a NullPointerException if it is null.
I changed the code a little bit, that way, it will not exceed if the file doesn't exist.
The Scanner input is local to your if statement. Your while (input.hasNextLine()) { statement will not work because of that. The Java compiler will treat input as a separate Scanner object and that is where the problems crop up, because to the Java compiler, the input that you are trying to use does not exist.
I would follow MouseEvent's suggested code as it does not run into the problem mentioned above.
The other answers have addressed your immediate question, but I want to point out a couple of other problems with your code:
The way that you are checking to see if the file can be opened is flawed. A better way to write the code is to attempt to open the file ... and retry when there is an exception. For example:
Scanner input = null;
do {
System.out.print("Input file name? ");
String fileName = sc.next();
File inputFile = new File(fileName);
try {
input = new Scanner(inputFile);
} catch (IOException ex) {
System.out.println("Cannot open: " + ex.getMessage());
}
} while (input == null);
Why is this better than calling File.exists()?
There are lots of reasons why you might be able to open a file. It might not exist at all. It might be a directory or a special file that can't be opened as a file. The application might not have permission. The file might be on a remote mounted file system and the remote mount might have just died.
There is a small time gap between the File.exists() call (and any others that you might make) and actually opening the file. In that time gap, it is possible that something to your program could do something to make the file unopenable; e.g. it could change its permissions or delete it.
The second problem is that your code potentially leaks a file descriptor because the scanner is not closed. In your specific application (as written) this doesn't matter because you are going to exit the application immediately after using the scanner. But if your weren't ... and this code was called lots of times ... you could find that you are unable to open files after a bit.
The correct way to deal with this would be to write your code something like this:
public static void main(String[] args) {
try (Scanner input = openInput()) {
while (input.hasNextLine()) {
// do stuff
}
}
}
This uses Java 7's new "try with resource" syntax, that ensures that the resource is closed when the try statement completes. (You can do the same thing in pre-Java 7 using a try / finally, but the code is a bit more cumbersome.)

Categories