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
Related
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.
I tried to put the file in as many places as I could to just see if any of them would work. I also tried to use the direct path but that also didn't work. I have a mac and am wondering if that is messing something up.
public static void main(String[] args) throws FileNotFoundException{
String nextString=null;
PopularName nextName;
String[] info=new String[5];
Scanner infile = new Scanner(new File("LastNames.txt"));
...
If you use
System.getProperty("user.dir");
You can get the current root directory of the project.
So if you put a file there you can read is like this:
new FileReader(System.getProperty("user.dir") + "/LastNames.txt");
There are more errors in your code:
Scanner takes as argument File (FileReader makes no sense here),
You are not taking care about exceptions -> either try-catch block or your method must throw it to upper level - see working example below.
The path to file should be relative to the root of project of absolute.
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new File("file.txt"));
while (inFile.hasNext()) {
System.out.println(inFile.next());
}
}
}
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.
I'm attempting to pass a File object to the Scanner constructor.
File file = new File("in.txt");
try{
Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
System.out.println(exp.getMessage());
}
I have an in.txt in the root of the project, src and bin directories in case I'm getting the location wrong. I have tried giving absolute paths as well. This line
Scanner fileReader = new Scanner(file);
always fails. Execution jumps to the end of main. If I misspell the name of the file, I get a FileNotFoundException. I'm on an Ubuntu 12.10 Java 1.7 with OpenJDK
I am running on linux and this is how you need to do it
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) throws IOException {
Scanner s = null;
try {
//notice the path is fully qualified path
s = new Scanner(new File("/tmp/one.txt"));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
here is the result :
source from Java Docs
If you do: File file = new File("in.txt"); in your java program
(let's assume it is named Program.java) then the file in.txt should
be in the working directory of your program at runtime. So if you
run your program like this:
java Program
or
java package1.package2.Program
and you are in /test1/test2/ when running this command,
then the file in.txt needs to be in /test1/test2/.
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();
}
}
}