i declared the Scanner infile before the try-exception but for some reason it says varible might not been initialized?
Scanner infile;
try
{
infile = new Scanner(file);
}
catch(FileNotFoundException f)
{
System.out.println("Wrong File Path");
}
while (infile.hasNext())
{
System.out.print("Testing While loop");
Consider what happens if an exception is thrown in the new Scanner constructor call. The constructor never completes, and so new Scanner(file) doesn't result in a value; what then for infile?
To correct it, move your while loop into the try block:
Scanner infile;
try
{
infile = new Scanner(file);
while (infile.hasNext())
{
System.out.print("Testing While loop");
}
}
catch(FileNotFoundException f)
{
System.out.println("Wrong File Path");
}
The purpose of exception handling, after all, is to get it out of the way of your main logic.
Imagine the situation where infile = new Scanner(file); throws an Exception. At the point of while (infile.hasNext()), infile would not have been initialised.
You can solve this problem by just changing Scanner infile; for Scanner infile = null;. But be aware that infile can still be null at this point if the said exception is thrown. You should put that part of the code inside the try block.
The best way to fix this would be to use Java's built in class error handling.
public static void main(String[] args) {
Scanner infile;
try {
infile = new Scanner(new File("filename.txt"));
} catch (FileNotFoundException f) {
System.out.println("Wrong File Path");
}
while (infile.hasNext()) {
System.out.print("Testing While loop");
}
}
This code will not compile because there is a possibility that the file will not be found and the error is not handled, but if you add throws FileNotFoundException to the main function declaration, the exception will be handled by the main function and won't cause any problems.
public static void main(String[] args) throws FileNotFoundException{
Scanner infile;
infile = new Scanner(new File("filename.txt"));
while (infile.hasNext()) {
System.out.print("Testing While loop");
}
}
Sorry if my explanation isn't very good, I'm only just starting out with Java myself.
Related
public static void textFileOpen(String fileName) throws IOException
{
while(true)
{
try
{
FileReader fileReader = new FileReader(fileName);
LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
BufferedReader bufferedReader = new BufferedReader(fileReader);
fileReader.close();
bufferedReader.close();
lineNumberReader.close();
}
catch(Exception ex)
{
System.out.println("File " + fileName + " does not exists! Please try again.");
}
}
}
I'm trying to let the user input file name again if exists. But it runs forever if user enter an exist file name. How can I fix it? Can anyone help, please? THank you
The cause is your use of try(input). As the scanner has already been closed after the first catch , it is not able to take any new input.
Remove the (input) and use a separate input.close should work.
You shouldn't close a Scanner that wraps System.in since System.in represents the standard input which is generally the computer keyboard. So when you close it, your program cannot receive input from the keyboard.
You should also not use exception handling to test a condition. You should use a conditional statement, like an if statement.
In order to test whether a file exists, you can call method isFile. The method returns...
true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise
When you create a FileWriter, it also creates the file if it doesn't already exist.
Here is code demonstrating the above.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) throws IOException {
System.out.println("Enter fileName: ");
Scanner input = new Scanner(System.in);
String fileName = null;
File file = null;
while (true) {
fileName = input.nextLine();
file = new File(fileName);
if (file.isFile()) {
System.out.println(file + " already exists! Please try again:");
}
else {
break;
}
}
FileWriter writer = new FileWriter(file);
}
}
Here, I can write on the file. But when I'm trying to read my file it's giving me "MyFile.txt" but my output should be " I'm 20"
What is wrong in my code?
import java.util.*;
class main{
public static void main(String[] args){
Formatter fr;
try{
fr = new Formatter("MyFile.txt");
fr.format("I'm %d",20);
fr.close();
}catch (Exception e){
System.out.println("Error");
}
try {
Scanner sc = new Scanner("MyFile.txt");
while (sc.hasNext()){
System.out.println(sc.next());
}
sc.close();
}catch (Exception e){
System.out.println("Error");
}
}
}
You're passing a string literal to the Scanner constructor.
Scanner sc = new Scanner("MyFile.txt");
That's the constructor that scans the string itself.
You want to pass it a File object instead:
Scanner sc = new Scanner(new File("MyFile.txt"));
Note: Writing to a file with a Formatter the way you do works because the Formatter constructor that takes a String assumes that the string is a file name. The Scanner constructor assumes that the string itself is the input, not a file name.
Alright so I have a very small program I'm working on designed to take the contents of a text file, test.txt, and put them in another empty file testCopied.txt . The trick is that I want to use Scanner and printWriter as I am trying to understand these a bit better.
Here is what my code looks like:
import java.io.*;
import java.util.*;
public class CopyA
{
public static void main(String [] args)
{
String Input_filename = args[0];
String Output_filename = args[1];
char r = args[2].charAt(0);
try
{
Scanner sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
PrintWriter printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine();
printer.write(s);
}
sc.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
This compiles, but when I look at testCopied.txt it is still blank, and hasn't had test.txt's content transferred to it. What am I doing wrong? Java IO is pretty confusing to me, so I'm trying to get a better grasp on it. Any help is really appreciated!
You have missed out flush() and close() for the PrintWriter object which you need to add
and then use the line separator using System.getProperty("line.separator") while writing each line into second file.
You can refer the below code:
PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");
sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}
Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).
I cannot call this function that handles a text file.
I try to call it but an exception is thrown. I tried various approaches but nothing has worked so far.
public static void spracujSubor () throws IOException {
File f = new File("test.txt");
Scanner sc = new Scanner(f);
try {
while(sc.hasNextLine()) {
String nazov = sc.next();
String model = sc.next();
double cena = sc.nextDouble();
Auto rep = new Auto(nazov, model,cena);
aPozicovna.aAuto.add(rep);
}
} catch(IOException ioe){
System.err.println(ioe);
}
sc.close();
}
First of all, we can't help you figure out what causes the IOException if you don't (at least) show us the exception's message. The complete stacktrace would be ideal, but the message you help a lot.
There are multiple places where the IOException could be thrown, including:
In the new Scanner(f) if the file doesn't exist, isn't readable, has the wrong pathname, and a few other cases.
In the various calls on the Scanner object in the loop, depending on your file syntax.
In the close() call ... in theory.
Some of these are inside the try-catch. Others are before or after it. For the cases inside the try catch, you are catching the exception, printing a message, and then proceeding as if nothing happened. That is bad. Here is a better structure ... that doesn't squash the exceptions.
public static void spracujSubor () throws IOException {
File f = new File("test.txt");
try (Scanner sc = new Scanner(f)) {
while(sc.hasNextLine()) {
String nazov = sc.next();
String model = sc.next();
double cena = sc.nextDouble();
Auto rep = new Auto(nazov, model,cena);
aPozicovna.aAuto.add(rep);
}
}
}
Note that since the Scanner is an Autocloseable, it will be closed automatically when you exit the try-with-resources.
I am writing a piece of code that returns a scanner for a user-input file name. Here's the code:
public static Scanner getInputScanner(Scanner console) {
System.out.print("Enter input file: ");
String fileName = "";
try {
fileName = console.nextLine();
File f = new File(fileName);
} catch (FileNotFoundException e) {
while (!(new File(fileName)).exists()) {
System.out.println(fileName + " (No such file or directory)");
System.out.print("Enter input file: ");
fileName = console.nextLine();
}
}
File f = new File(fileName);
return new Scanner(f);
}
I am getting two errors:
Compression.java:49: error: exception FileNotFoundException is never thrown in body of corresponding try statement
} catch (FileNotFoundException e) {
^
Compression.java:57: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
return new Scanner(f);
I can't figure out why the try block isn't throwing an exception, since the user could input an invalid file name.
Thanks for any help.
EDIT: changed the FileNotFoundException to a NullPointerException and that fixed the first problem. Now, however, I get an error that my return statement is throwing an unreported FileNotFoundException. But this code wouldn't execute unless the file is valid, right? Is Java blind to this, and requires I catch the exception anyway?
The FileNotFoundException is neither thrown by Scanner#nextLine() nor by creating a new File object (File#new(String)). Both functions do nothing that is related to file I/O.
Scanner.nextLine() operates on an alread existing input source
File#new() creates simply a new File object that points (file name) to an (maybe existing) actual file.
The creation of a new Scanner object in contrast, involves creating a new InputStream, so it actually touches the supplied file by opening it.
From java.util.Scanner:
public Scanner(File source) throws FileNotFoundException {
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
The documentation clearly states that the File(String pathname) constructor can only throw NullPointerException and NOT FileNotFoundException.
If you want to see if the file name is valid, use f.exists().
return new Scanner(f);
throws error when file is not found, it can't return the scanner(f) . so should be wrapped in try-catch block.
or you need to make the getInputScanner to throw the FileNotFoundException
File f = new File(fileName);
does not throw an exception if the file does not exist. A File object is really just a filename; it does not refer to the actual file. If the file does not exist, you will get an exception when you try to use it.
new Scanner(f) is the part that throws a FileNotFoundException.
You can always call File.exists() before you construct your Scanner and if you use an infinite loop you can simplify your logic and eliminate those errors. Something like,
public static Scanner getInputScanner(Scanner console) {
while (true) {
System.out.print("Enter input file: ");
String fileName = console.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " (No such file or directory)");
continue;
}
try {
return new Scanner(f);
} catch (FileNotFoundException e) {
// This shouldn't happen.
e.printStackTrace();
System.out.println(fileName + " (No such file or directory)");
}
}
}