unable to read file in java - java

I am trying to have user input an interger, based on the integer value, I am calling mix function to read in the file contents as code shows below. I am getting, this error:
Project2.java:43: variable urlScan might not have been initialized
while (urlScan.hasNext())
^
Project2.java:34: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
fileScan = new Scanner (new File("input.txt"));
^
Any ideas, what I might be doing wrong here?
import java.util.Scanner;
import java.io.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
System.out.println(input);
if(input==1) {
mix();
}
else{
System.out.println("this is exit");
}
}
public static void mix()
{
String url;
Scanner fileScan, urlScan;
fileScan = new Scanner (new File("input.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
url = fileScan.nextLine();
System.out.println ("URL: " + url);
//urlScan = new Scanner (url);
//urlScan.useDelimiter("/");
// Print each part of the url
while (urlScan.hasNext())
System.out.println (" " + urlScan.next());
System.out.println();
}
}
}

The errors are pretty expressive.
Initialize your urlScan local variable(local variables don't get default values)
Wrap the fileScan = new Scanner (new File("input.txt")); around try/catch. or declare that your method might throw FileNotFoundException in your method signature. (new File(str) might throw FileNotFoundException which is a checked exception and compiler will force your handled it).

First, urlScan isn't initialized.
Second, you should surround fileScan = new Scanner (new File("input.txt")); with an try/catch for FileNotFoundException.

Local variables must be initialized before use, so uncomment this line:
urlScan = new Scanner (url);

Related

What scenario would create an nosuchelementexception with nextLine()?

The documentation for nextLine() says that it can throw a nosuchelementexception. But when using the nextLine() to get input for the Scanner as demonstrated in the following code, the nosuchelementexception is not thrown, The only thing that happens is by pressing "Enter" two times the programs just ends. I submitted the same code for an evaluation to an online system, there also the system said that the code throws a nosuchelementexception
What sort of an input would produce a nosuchelementexception?
String input = "";
Scanner sc = new Scanner(System.in);
input += sc.nextLine() + " ";
input += sc.nextLine() + " ";
System.out.println(input);
Here’s an example where the standard input (i.e. System.in) is piped from another application:
echo 'one line only' | java Read
Or read from a file:
java Read <file_with_one_line.txt
Or using interactive user input:
java Read
I am entering one line
Ctrl+D
These examples assume that you’ve compiled the code you’ve posted (wrapped into a class Read) to Read.class in the same directory.
import java.util.Scanner;
class Read {
public static void main(String[] args) {
String input = "";
Scanner sc = new Scanner(System.in);
input += sc.nextLine() + " ";
input += sc.nextLine() + " ";
System.out.println(input);
}
}
javac read.java
I think this is possible when reading files:
I created a new txt-file without any content (test.txt) in it and ran the following code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("test.txt");
Scanner sc = new Scanner(file);
String str = sc.nextLine();
}
}
The result:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Test.main(Test.java:9)
Edit
It can also appear with System.in because when closing one scanner it appears to also close System.in.
Consider the following code:
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
sc.nextLine();
sc.close();
sc2.nextLine();
}
}
This throws the following exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Test.main(Test.java:10)
This happens because sc (with access to System.in) was closed. This causes that System.in is not accessible anymore and therefore sc2 doesn't work properly and throws an exception.

Creating a File that will read a txt file

So i am currently trying to figure out how my code can read my txt file. My objective is to prompt what ever i have for initialization, then ask me to type a number but 0 to get a message that i have written on my txt file. Then finally by finishing by typing 0 and getting what ever message i have for the finish. I have read online articles but i still have trouble. This is what i have so far:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.ArrayList;
public class FortuneFile
{
static Scanner keyboard;
static int inputLine;
static Scanner inputFile;
static boolean done;
public static void main(String[] args) throws Exception
{
initialization();
while (inputFile.hasNext())
while (!done)
{
mainLoop();
}
finish();
}
public static void initialization() throws Exception
{
Scanner inputFile = new Scanner(new File("FortuneCookie.txt"));
keyboard = new Scanner(System.in);
done = false;
System.out.println("");
System.out.println("Welcome to the Command Box FortuneCookie game!");
System.out.println("====================================================================");
System.out.println("Dare to try your luck?... You could be a Winner or a Looser!");
System.out.println("");
System.out.println("Enter \"0\" if you are scared, or if you are brave, try any number: ");
System.out.println("====================================================================");
}
public static void mainLoop() throws Exception
{
inputLine = inputFile.nextInt();
i++;
if (keyboard.equals("0"))
{
done = true;
}
else
{
{
System.out.println("");
}
System.out.print("Care to try again? ");
System.out.println("");
}
}
public static void finish()
{
System.out.println("====================================================================");
System.out.println("Thanks for playing along. I hope you are not traumatised!");
}
}
Thank you!! :)
There are some problems in your code:
First, You missed declaring i in your mainLoop() method so that it can't compile successfully.
Second, keyboard is a Scanner object which can't be compared with String object 0 by equals()
keyboard is a Scanner object. It can't be compared like String with equals("0").
When you are reading nextInt(), store the value in int variable and compare thar value is 0 or not to end the loop.
You are using keyboard.equals() which is wrong as keyboard is a Scanner object and not a String. You should use keyboard.nextLine() to get the input from the user and store this in a String. So you'll have something like,
String holder = keyboard.nextLine();
An easier way to to this would be to read in the integer using something like,
int holder = keyboard.nextInt();
and then compare this integer with 0 using ==
Check out this link for more information on Scanners in Java;
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Also in initialize() you're making a new local Scanner inputFile that you use in the method. The problem with this is that when you make calls to inputFile outside initialize() you'll run into problems as inputFile outside initialize() is not defined to operate on the file you're using. This is a scope resolution issue.
You'd just want to do, inputFile = new Scanner(new File("FortuneCookie.txt"));
Also make sure that this text file is in the same directory as your project's, otherwise you'll have to describe the complete path.
Make sure you understand your scope resolution as this can cause various problems.
I hope this was helpful!
Good luck!
Try this:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.ArrayList;
public class FortuneFile
{
static Scanner keyboard;
static int inputLine;
static Scanner inputFile;
static boolean done;
static String myMessage;
public static void main(String[] args) throws Exception
{
initialization();
//create an object that reads integers:
Scanner Cin = new Scanner(System.in);
inputLine = Cin.nextInt();
while(inputLine != 0){
System.out.println("");
System.out.print("Care to try again? ");
System.out.println("");
System.out.println("Enter another integer: ");
inputLine = Cin.nextInt();
}
System.out.println(myMessage);
finish();
}
public static void initialization() throws Exception
{
Scanner inputFile = new Scanner(new File("C:/FortuneCookie.txt"));
//keyboard = new Scanner(System.in);
//Read the first line
myMessage = inputFile.nextLine();
//System.out.println(myMessage);
done = false;
System.out.println("");
System.out.println("Welcome to the Command Box FortuneCookie game!");
System.out.println("====================================================================");
System.out.println("Dare to try your luck?... You could be a Winner or a Looser!");
System.out.println("");
System.out.println("Enter \"0\" if you are scared, or if you are brave, try any number: ");
System.out.println("====================================================================");
}
public static void finish()
{
System.out.println("====================================================================");
System.out.println("Thanks for playing along. I hope you are not traumatised!");
}
}
You can remove my main loop and put it in another procedure if you want. I am checking the input with 0. If it is zero, it is the end. If not, it will remain in the loop. I put my file in drive c. You can change your address to your file location. This is the result:
And this was the body of my text file:
I hope this solves your problem. Please let me know if you have any other question.

Read numbers separated by ":" from file - Java

I'm having some problems reading some numbers separated by ":" from a txt file in java.
This is what i have so far:
public static void main(String []args) {
Scanner keyb = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFile = keyb.nextLine();
System.out.print("Enter output file name: ");
String outputFile = keyb.nextLine();
File file = new File(inputFile);
try {
Scanner sc = new Scanner (file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("File not found!");
}
}
File numbers.txt
12.1:15.42
0.23:0.25
-9.2:-8.1
13.5:15.9
1024:1023.9
1.0e-3:1.0e-4
15.92:-9.35
18.26:6.4
55.931:55.930
256:512
I dont understand why its not being read...any help would be much appreciated! thank you!
I tried testing your program and got correct output. Take a look
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
File file = new File("numbers.txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
Output:
12.1:15.42
0.23:0.25
-9.2:-8.1
13.5:15.9
1024:1023.9
1.0e-3:1.0e-4
15.92:-9.35
18.26:6.4
55.931:55.930
256:512
I recommend using java.util.BufferedReader to read a file. There generally easy to use compared to the Scanner class.
...
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String inLine; //Buffer used to store the current line
while ((inLine = br.readLine()) != null) //keep reading until we reach the end of file
{
System.out.println(inLine);
}
Tutorial: Java >> BufferedReader
Make use of the split method in the string class and equate the output to an array,each index will have a different number if they are all indeed seperated by the same character that you have specified above: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html and http://www.coderanch.com/t/385246/java/java/split-method-String-API might help but I strongly recon u download all the APIs

FileNotFoundException occurs due to my outputStream method

Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.

Printing string variable in Java

I'm getting some weird output when running (seemingly simple) code. Here's what I have:
import java.util.Scanner;
public class TestApplication {
public static void main(String[] args) {
System.out.println("Enter a password: ");
Scanner input = new Scanner(System.in);
input.next();
String s = input.toString();
System.out.println(s);
}
}
And the output I get after compiling successfully is:
Enter a password:
hello
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=5][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Which is sort of weird. What's happening and how do I print the value of s?
You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,
Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);
Please read the tutorial on how to use it as it will explain all.
Edit
Please look here: Scanner tutorial
Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.
You could also use BufferedReader:
import java.io.*;
public class TestApplication {
public static void main (String[] args) {
System.out.print("Enter a password: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String password = null;
try {
password = br.readLine();
} catch (IOException e) {
System.out.println("IO error trying to read your password!");
System.exit(1);
}
System.out.println("Successfully read your password.");
}
}
input.next();
String s = input.toString();
change it to
String s = input.next();
May be that's what you were trying to do.
This is more likely to get you what you want:
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
If you have tried all the other answers, and it still hasn't work, you can try skipping a line:
Scanner scan = new Scanner(System.in);
scan.nextLine();
String s = scan.nextLine();
System.out.println("String is " + s);

Categories