My java code is flawed, but i dont understand why - java

I am very new at java and my be missing something very basic. When i run my code i am trying to add value to accounts created in the code. When i try to run the code i recieve an error that a file cannot be found, but i thought that the file was created inside the code.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class DoPayroll
{
public static void main(String args[])
throws
IOException
{
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
for (int empNum = 1; empNum <= 3; empNum++)
{
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner)
{
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
}
once run i recieve the following error
Exception in thread "main" java.io.FileNotFoundException: EmployeeInfo.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at DoPayroll.main(jobexe.java:11)
i thought that in the above code using new Scanner(new File("EmployeeInfo.txt") would create the new file once i input a value. Please give me a simple solution and an explanation.

It will create a new file when you write to it. However to read from it, it must already exist. You might like to check it exists with
File file = new File("EmployeeInfo.txt");
if (file.exists()) {
Scanner diskScanner = new Scanner(file);
for (int empNum = 1; empNum <= 3; empNum++)
payOneEmployee(diskScanner);
}

The File object can't find the filename you've passed. You either need to pass the full path of EmployeeInfo.txt to new File(...) or make sure current working directory is the directory that contains this file.

The File constructor does not create a file. Rather, it creates the information in Java needed to access a file on disk. You'd have to actually do file IO in Java using the created File for a new file to be created.
The Scanner constructor requires an existing File. So you need a full path to the real, valid location of EmployeeInfo.txt or to create that file using File I/O first. This tutorial on I/O in Java will help.

You are mistaking instantiating an instance of class File with actually writing a temp file to Disk. Take this line
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
And replace it with this
File newFile = File.createTempFile("EmployeeInfo", ".txt");
Scanner diskScanner = new Scanner(newFile);
Edit: Peter makes a good point. I'm face palming right now.

You thought wrong :D A Scanner needs a existing file, which seems quite logical as it reads values and without a existing file its difficult to read. The documentation also states that:
Throws:
FileNotFoundException - if source is not found
So, in short: You must provide a readable, existing file to a scanner.

As the other answer explain, the file is not created just by using new File("EmployeeInfo.txt").
You can check is the file exists using
File file = new File("EmployeeInfo.txt");
if(file.exists()) {
//it exists
}
or you can create the file (if it doesn't exists yet) using
file.createNewFile();
that method returns true if the file was created and false if it already existed.

Related

How to get File name from cmd argument to create a copy?

I'm working on a program that reads from a file with a custom extension I made. The idea is that an error report is created every time a file is read. The error report must be in whatever folder the source file was called from. The error file is a copy of the source file, but it has a line number at the beginning of each line and indicates at the end of the line if an error occurred at that line.
(I'm not trying to set up the numbering on this question, this question is just about creating the copy)
So for example, when I call my program from the command prompt:
C:\MyLocation>java =jar myJavaProgram.jar myFileToRead.CustomExtension
Asides from reading the file, it should also create a copy at the same location called myFileToRead-ErrorReport.txt
Additionally: If the source file has no extension, I have to assume that it's still the correct extension, so there won't always be a '.myCustomExtension' segment to replace into .txt
The problem is that I don't know how to grab the file name, because it's coming from the args list of the main method. I am using the following to read the file
public static void main(String[] args) throws FileNotFoundException {
try{
File inputFile = new File(args[0]);
Scanner sc = new Scanner(inputFile);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("File not found.");
}
}
So how can I get that file name to make something like
File errorReport = new File("./" + inputFileName + ".txt"); ?
First the code. The explanations appear after the code.
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("ERROR: Missing filename argument.");
}
else {
String filename = args[0];
if (filename.length() == 0) {
System.out.println("ERROR: Empty filename argument.");
}
else {
if (!filename.endsWith(".CustomExtension")) {
filename += ".CustomExtension";
}
String name = filename.substring(0, filename.indexOf(".CustomExtension"));
name += "-ErrorReport.txt";
File inputFile = new File(filename);
File directory = inputFile.getParentFile();
File errorReport = new File(directory, name);
System.out.println(errorReport.getAbsolutePath());
}
}
}
I make it a habit of checking the parameters. Hence I first check that the file name was supplied. If it was, then I check that it is not an empty string. Note that I have omitted some checks, for example checking whether the named file exists and is readable.
You wrote in your question that the file name argument may or may not include the .CustomExtension. Hence I check whether the supplied name ends with the required extension and append it if necessary. Now, since I know what the file name ends with, that means that the required part of the name is everything up to the extension and that's what the call to substring() gives me.
Once I have the required name, I just append the part that you want to append, i.e. -ErrorReport.txt.
Method getParentFile() in class java.io.File returns the directory that the file is located in. Hence I have the directory that the input file is in. Finally I can create the error report file in the same directory as the input file and with the desired file name. For that I use the constructor of class java.io.File that takes two parameters. Read the javadoc for details.
Note that creating a File object does not create the file. Creating an object to write to the file does, for example FileWriter or OutputStreamWriter.
Here is the code example to create a file, with filename passed from cmd line as argument and to get the same file name :
Class Demo{
public static void main(String[]args){
String path ="<path of file>"
String name= args[0];
File f = new File(path+name+".txt");
f.createNewFile(); //create file
System.out.println(f.getName()); // will give you the file name
}
}
cmd line : java -cp . Demo.java <filename>
Note : '.' used in the cmd if your class file is present in current dir
You can refer the code and modify to suit your requirement.
Hope this is what you are looking for.

File (.txt) cannot be found

I am creating a stock market simulator (beginner) and I made a .txt file to save the stock symbol and name within a file. I am having an issue where my code is unable to find the file on my desktop.
public static void load() throws FileNotFoundException {
File file = new File("/Users/dhruvchaudhari/Desktop/stocks.txt");
Scanner scan = new Scanner(file);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
The error it is throwing is as such
java.io.FileNotFoundException: /Users/*username*/Desktop/stocks.txt (No such file or directory)
I'm on Mac and I checked the directory for the file directory and it should be correct. Any suggestions?
You can check the current working directory to confirm the path of your file by adding System.out.println("Working Directory = " + System.getProperty("user.dir"));
this will return the path you can debug this to get the idea of path in your application.
Also you can add read the file if its not there the code will create it for so you can add your metadata into the generated file.
By using this approach I hope you can move ahead.
public static void load() throws IOException {
File yourFile = new File(path);
yourFile.createNewFile(); // if file already exists will do nothing
Scanner scan = new Scanner(yourFile);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
Obviously your path is wrong or the file doesn't exist. You can use the if statement to determine whether the file exists first, and create the file when it does not exist.

File not found java

I have a problem when reading a text file in java. The class is FlashCardReader and I have the following constructor that handles the part of the reading.
public FlashCardReader( String fileName ) {
try{
reader = new BufferedReader(new FileReader(fileName));
}catch(FileNotFoundException e){
System.out.println("The file was not found or the name may be wrong!");
}
}
My main method looks like this:
public static void main(String[] args) {
FlashCardReader fcr = new FlashCardReader("Questions.txt");
}
And the final output is: The file was not found or the name may be wrong!
Some help would be greatly appreciated, cheers!
You can print the current directory of your java program where it is executed from with this java code,
System.out.println("CurrentDir: " + (new File(".").getCanonicalPath()));
Say it prints,
CurrentDir: D:\pkr\test
Then you can correctly choose a path through which your file can be correctly located.
Most likely, your src folder should be in test directory and in that case you can either move your file from src folder to test folder or refer your file in your code like this,
..\\Questions.txt
which should be able to read your file.
Let me know if this works.

Why is my scanner not reading from my file?

I'm trying to get my program to read data from a text file and store it in an array. The text file contains data about a planet.
Here is an example:
Mercury
4.151002e10
2.642029e10
-1.714167e9
-3.518882e4
4.355473e4
6.785804e3
3.302e23
My file is named test.txt. It lives in the same directory as my class.java file. I've used System.out.println(new File("test.txt").getAbsolutePath()); to check if the directory path is correct, which it was, and I used System.out.println(new File(".")); to check if it was in the same directory that the code was trying to compile in, which again it was (outputted just a dot which I was led to believe meant it was in the correct directory). I've tried different ways of finding the file, such as renaming it to something else to check it wasn't a keyword, changing the encoding of the file to Unicode, or UTF-8, or ANSI, none of which worked, using .\test in the file to look in the same directory, none of which worked.
Here is my code:
public static void defaultPlanetArray(){
Planet[] solarSystem;
solarSystem = new Planet[9];
PhysicsVector dummyAcceleration = new PhysicsVector();
System.out.println(new File("test.txt").getAbsolutePath());
System.out.println(new File("."));
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
}
catch(FileNotFoundException e){
System.out.println("File not found!");
}
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
PhysicsVector and Planet are both classes I have created. PhysicsVector and the rest of Planet apart from this excerpt compile with no problems. When I try to compile this specific bit of code, I get:
.\Planet.java:65: error: cannot find symbol
while(i<9 && scnr.hasNextLine()){
^
I'm guessing this means that the variable scnr is not being created in the try section because it cannot find the file. I think this because when I don't include the try and catch blocks, I get:
.\Planet.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner scnr = new Scanner(file);
^
I've also tried the catches FileNotFoundException when I'm first creating the method but that gives me the same error as immediately above.
I could just set the values in the program, but that would give a lot of unnecessary code and be rather inefficient I think.
So my question is, how do I get the scanner to read my values from the file?
As #Lalit Verma pointed the scnr variable you defined lives inside the try - catch block.
Change the code to:
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
}catch(FileNotFoundException e){
System.out.println("File not found!");
}

Java not creating file

package com.company;
public class Main {
public static void main(String[] args) {
java.io.File file = new java.io.File("image/us.gif");
System.out.println("Does it exist:" + file.exists());
System.out.println("The file has " + file.length() + "bytes");
System.out.println("Can it be read? " + file.canRead());
}
}
I copied this code from my book Introduction to Java Programming, and it compiles correctly but it doesn't create the file, and returns false and zero bytes for the methods. Can someone help please I will give best answer.
You will have to create the file manually unless it already exists. Creating a new File object should not be confused with creating a file in the filesystem.
To create the file you will have to use the method createFile(); which exists in the class File:
File someFile = new File("path.to.file");
someFile.createFile();
It would also be a good idea to check if the file exists before creating it to avoid overwriting it. this can be done by:
File someFile = new File("path.to.file");
if(!someFile.exists()) {
someFile.createFile();
}
This will create a new empty file. That means that it's length will be 0.
To write to the file you will need a byte stream. For example, using a FileWriter:
File test = new File("SomeFileName.txt");
FileWriter fw = new FileWriter(test);
fw.append("Hello! :D");
fw.close();
Note: Some methods i used in the examples above throw exceptions which you will have to handle.

Categories