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.
Related
somefile.txt has some input as below, and newfile.txt is empty.
China
1330044605
India
1147995898
United States
303824646
Both files are on my desktop.
public class NextMethod {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("/home/cyn/Desktop/somefile.txt");
Scanner in = new Scanner(inputFile);
PrintWriter writer = new PrintWriter("/home/cyn/Desktop/newfile.txt");
while (in.hasNextLine()) {
String coName = in.nextLine();
int peopCo = in.nextInt();
in.nextLine();
writer.println(coName);
writer.println(peopCo);
}
in.close();
writer.close();
}
}
i was able to duplicate your problem by adding a blank line to the end of someFile.txt.
this is consistent behavior with what's documented in the javadoc.
Throws: NoSuchElementException - if no line was found
check to make sure you don't have any unintended whitespace in your input document.
So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
String save = new String();
while(sc.hasNextLine())
{
save=sc.nextLine();
}
byte buf[]=save.getBytes();
FileOutputStream fos = new FileOutputStream(f);
for(int i=0;i<buf.length;i++)
fos.write(buf[i]);
if(fos != null)
{
fos.flush();
fos.close();
}
}
If anyone has a way to fix the code or even a better idea for saving please let me know, thanks
You are replacing save value in every single nextLine.
Change this line:
save = sc.nextLine();
to this one:
save += sc.nextLine();
Also, it's better to use a FileWriter when you are writing String to a file.
And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
Look at code included below:
public static void main (String[] args) throws Exception
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine())
{
builder.append(sc.nextLine() + "\n");
}
String save = builder.toString();
FileWriter writer = new FileWriter(f);
writer.write(save);
writer.close();
}
Also close() implicitly calls flush().
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.
I am working on an assignment and cannot get this method to produce the correct output to the file. I am supposed to get the mean and write it to the file. Their is the StatsDemo class and the StatsFile class. I am kind of a beginner at Java so I'd like just a little help. My method in the StatsFile class is currently like this:
//returns the calculated arithmetic average
public double calculateMean(String filename) throws FileNotFoundException
{
// declare variables step 5
double accumulator = 0.0;
int counter =0;
String line;
try{
File input = new File(filename);
//create a Scanner object passing it the File object
Scanner keyboard = new Scanner(input);
//for (int i = 0; i < input.length(); i++){
// Read a double from the file.
while(keyboard.hasNextDouble()){
accumulator += keyboard.nextDouble();
// Add to counter
counter++;
}
keyboard.close();
}catch(FileNotFoundException e){
}
return (accumulator/counter);
}
The demo is as such:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class StatsDemo {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
DecimalFormat threeDec = new DecimalFormat("0.000");
Scanner keyboard = new Scanner(System.in);
String filename; // the user input file name
System.out.print("Enter the file name: ");
filename = keyboard.nextLine();
FileStats fileObj = new FileStats(filename);
try{
PrintWriter name = new PrintWriter("Results.txt");
name.println("mean = " + threeDec.format(fileObj.getMean()));
name.println("Standard Deviation = " + threeDec.format(fileObj.getStdDev()));
name.close();
}catch(IOException e){
System.out.println("Error");
}
}
}
The catches and throws still kind of confuse me. My issue is that it currently gives me a question mark instead of the mean when i open the file. Any help will be appreciated.
If an exception that occurs within the try block, control jumps to the catch block. You should think about what should happen in that case. You may be able to correct the problem and continue; you may wish to look at the problem and rethrow and exception, or you may wish just to let your caller handle the problem. In the last case, you don't need a catch at all, you can just need a throws on your method declaration.
Catching an exception and doing nothing is rarely a good idea as the problem is just being ignored. Remember that code flow will carry on after the catch clause unless another exception is thrown, so if the file does not exist, you will still process the return (accumulator/counter) line, which is not what you want.
Looking at your code, your method already throws a FileNotFoundException, so just remove the try and the catch.
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)");
}
}
}