FileNotFoundException for a file I know is in the directory - java

In the following program I am trying to read from the Hw1_1.java source code. I get a FileNotFoundException every time (probably for a good reason). I know the program isn't complete as I am just trying to stop getting the exception. I am at a loss.
If someone could point me in the right direction I would greatly appreciate it.
package hw1_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Hw1_1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the name of a java source code file");
String inputFileName = console.next();
String outputFileName = (inputFileName + ".txt");
try {
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
while ( in .hasNextLine()) {
String line = console.nextLine();
out.println(line);
}
in .close();
out.close();
} catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
}
}

It's really a good idea - to first check the user directory of your java program. Once you know, you can easily debug the FileNotFoundException issue.
You can simply print the user directory from following code.
System.out.println(System.getProperty("user.dir")) ;
Using absolute path for the file is another way of solving problem, but that's a little irregular way of doing.

You need to be aware of path complexity in your code, especially if you are using IDE as IDE can have a different execution path
Based on your code, if the value inputFileName is just the file name (let's say log.txt) and the execution path is actually different, then your code will never find the path
The quickest and dirty solution to quickly prove this is to use the full absolute path as the value of inputFileName for example:
String inputFileName = "/var/tmp/log.txt"
or
String inputFileName = "C:/workspace/temp/log.txt"
Once this verifies that your code can read the file, then you can start handling the path issue, good luck.

Related

FileReader not working in Java

I'm trying to read from a file and it's not working correctly. I've looked at many examples on here and the method I'm using is borrowed from an answer to someone else's question. I'm aware you can use bufferedreader but I'd like to stick with what I know and am learning in my classes right now. When I run this code I just get a blank line, but the file contains 4 lines of information.
import java.io.*;
import java.util.Scanner;
import java.lang.StringBuilder;
import java.io.File;
import java.io.FileInputStream;
public class fileWriting{
public static void main(String[] args) throws IOException{
//Set everything up to read & write files
//Create new file(s)
File accInfo = new File("accountInfo.txt");
//Create FileWriter
Scanner in = new Scanner(new FileReader("accountInfo.txt"));
String fileString = "";
//read from text file to update current information into program
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
fileString = sb.toString();
System.out.println(fileString);
}
}
My file contains the following text:
name: Howard
chequing: 0
savings: 0
credit: 0
One of the advantages of using something like BufferedReader over using Scanner is that you will get an exception if the read fails for any reason. That’s a good thing—you want to know when and why your program failed, rather than having to guess.
Scanner does not throw an exception. Instead, you have to check manually:
if (in.ioException() != null) {
throw in.ioException();
}
Such a check probably belongs near the end of your program, after the while loop. That won’t make your program work, but it should tell you what went wrong, so you can fix the problem.
Of course, you should also verify that accountInfo.txt actually has some text in it.

Another java.io.FileNotFoundException (The system cannot find the file specified) thread

I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".

Java.IO.Filenotfoundexception error, Can't find a file that exists in C:

I am recently beginning programming and cannot get my program to find a file, then read input from it. Says the file does not exist. Here is my code.
import java.util.*;
import java.io.*;
public class assignment3 {
public static void main(String args[]) throws IOException {
PrintWriter pw = new PrintWriter("C:\\file\\Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n" +
"---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.next();
File f = new File(filename);
System.out.println(f);
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
At line Scanner inputfile = new Scanner(f);. The error mentioned appears. Also when prompted to type in the file name in the program, i put "C:/Games.txt".....but when i got the filename to be printed out the filename is registerd as C:\Games.txt....why is the forward slash turning into a backslash. Thank you for taking the time to help me.
Make sure the folder named "file" exists (for creating a file). It might throw that error if it's not there. For reading you need to have the proper rights.
why is the forward slash turning into a backslash?
Because you're on Windows, and directories are natively separated by a \
Next, you don't appear to be writing with your PrintWriter. And if you want to check for a file that exists, call File#exists().
File f = new File(filename);
if (f.exists()) {
System.out.println(f);
Scanner inputFile = new Scanner(f);
while (inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}
} else {
System.out.println(f.getPath() + " does not exist");
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Answer {
public static void main(String args[]) throws IOException, FileNotFoundException {
// Have to throw a FileNotFoundException just in case an error occurs the compiler needs to know how to process the error.
PrintWriter pw = new PrintWriter("C:/file/Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out
.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n"
+ "---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.nextLine(); //Input for strings
System.out.println(filename);
File f = new File("C:/file/"+filename+".txt"); //Must have a location for your files
f.createNewFile(); //The file's pathname is the only thing that you can supply when you instantiate the object
//you actually have to invoke the createNewFile method upon the object.
if(f.exists()) { //Don't be afraid to check your code this is a must for every programmer.
System.out.println("Good! The File Exists");
}
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
When you create a file you always have to throw a FileNotFoundException if you do not the compiler will not know what to do if the error occurs. Use / when specifying directories of files.
\ is generally used as an escape sequence and when you type this \ \ your basically telling it to escape itself this code is useful in other situations but not this one.
You can NOT create a new file by the initiation of the object you always have to invoke the createNewFile method upon the object so that you can create a new file. This is because no constructors automatically call the createNewFile method in the class. You might be wondering what the words in the parameter are, they just serve the purpose of naming the file directory. I have found a helpful link if you want to review creating Files. Just look under the constructors tab. API Files Class
BE SURE! to always check your code, it does not matter how good of a programmer you are. You ALWAYS have to check for errors and if you make a game, and don't know where the error is among the millions of lines of code. You are going to have a hell of a time.
Lastly, I was not sure what you were trying to do after the if statement, but you will receive an error after the if statement, so if you want to ask me how to help with that just type in the comments of my post.

File Not Found Exception, Identical Directory Exists

However the file appears to be there. Under FileOne.txt's properties the directory is listed as;
C:\Users\Rig\Desktop\Java
The code is as follows,
import java.io.File;
import java.util.Scanner;
class Parse{
public static void main(String args[]){
System.out.println("Hey gurl hey World!");
File file = new File("C:\\Users\\Rig\\Desktop\\Java\\FileOne.txt");
Scanner input = new Scanner(file);
while(input.hasNext()) {
String nextToken = input.next();
System.out.println("Hey gurl hey World!");
}
input.close();
}
}
Any help or insight would be appreciated!
Edit: This issue has been resolved, consult Masud's answer.
If your path is correct than you should read your file. But, you need to catch or throw FileNotFoundException to compile or run.
public static void main(String args[]) throws FileNotFoundException{
.....
}
you wrongly typed the file type txt instead you give Txt.
File file = new File("C:\\Users\\Rig\\Desktop\\Java\\FileOne.txt");
The issue seems to be your FileName is FileOne.Txt and the whole file name is FileOne.Txt.txt including textpad extension.
So the whole path will be
C:\Users\Rig\Desktop\Java\FileOne.Txt.txt

What is wrong? Why is it giving me unreported exception java.io.FileNotFoundException?

What is wrong? Why is it giving me "unreported exception java.io.FileNotFoundException"? This is an exercise for a book I'm learning from and I just can't figure out what is wrong, it looks exactly like and example they provided. This file is in the same folder.
import java.io.*;
import java.util.*;
public class Mine
{
public static void main(String[] args)
{
Scanner inFile =
new Scanner(new FileReader("Ch3_Ex7Data.txt"));
PrintWriter outFile = new PrintWriter("Ch3_Ex7Output.dat");
String lastName;
lastName = inFile.next();
System.out.println(lastName);
inFile.close();
outFile.close();
}
}
FileNotFoundException means, well... then file can't be found.
Make sure the "Ch3_Ex7Data.txt" file is a direct child of the project root directory. Reading a file, that's where your IDE will first search, when you're just using this ("Ch3_Ex7Data.txt") relative path.
ProjectRoot
Ch3_Ex7Data.txt
src
Note: in the future, you will learn that is not the best solution for production/deployment purposes, when the file is t become an embedded resources, but the above should work for you, until you delve deeper towards the production stage.
UPDATE to OP comment
" And should I get in the habit of the other method now? and if so what does that look like"
You'll want to learn it in the future, but you will first need to learn about InputStreams. So it may be a but premature. But if you wan't to learn more, just search "Reading a text file from a jar". You'll find answers that'll look like this
InputStream is = getClass().getResourceAsStream("Ch3_Ex7Data.txt");
Where you file would now have to be located in the class path, so your file structure would instead change from the above structure to this below
ProjectRoot
src
Ch3_Ex7Data.txt
FileNotFoundException is a checked exception. You have to try/catch for it. It doesn't matter whether the file exists or not. FileNotFoundException extends IOException so you only need to catch IOException. This should compile:
import java.io.*;
import java.util.*;
public class Mine
{
public static void main(String[] args)
{
Scanner inFile = null;
PrintWriter outFile = null;
try {
try {
inFile = new Scanner(new FileReader("Ch3_Ex7Data.txt"));
outFile = new PrintWriter("Ch3_Ex7Output.dat");
String lastName;
lastName = inFile.next();
System.out.println(lastName);
} finally {
if(inFile != null)
inFile.close();
if(outFile != null)
outFile.close();
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

Categories

Resources