Eclipse unable to import File object FileNotFoundException - java

I am new for Importing file using scanner line by line reader .When i have import file it's working correctly , but some other system(i.e. colleague system) same project and same database connection while importing file error like Java.io.FileNotfoundException local drive fake path directory (e.g: "c:\fake path\db.sql").
public boolean checkfile(String dbfile){
File obj = new File(dbfile)
Scanner scr = new Scanner(obj );
try{
while(scr .hasNext()){
String scr_line = scr.nextLine();
System.out.println(scr_line );
}
}catch(Exception ex){
System.out.println(ex.tostring());
}
}
Above code File obj = new File(dbFile) this line error message showing like Java.io.FileNotFoundException local drive fake path directory . can any please help me where i have done mistake above this code .

1 , File you try read is not available in your colleague system or where you run this java program
2 , check this file "c:\fake path\db.sql" is available or not in where you run this java program
3 , When you run the program make sure you are sending the file path based on the Environment(Windows,unix etc.....)
4 , check File availability first
try
{
File f = new File("c:\fake path\db.sql");
if(f.exists())
{
//read the file
}
}
catch(Exception e)
{
// do some work
}

Related

how to locate a file?

Hi I want to know how the program can locate a file.
For example. I have a class
public class MiReader {
private File file;
private BufferedReader bufferedReader;
public MiReader(String dir) {
try {
file= new File(dir);
bufferedReader = new BufferedReader(new FileReader(file));
} catch (Exception ex) {
Logger.getLogger(MiReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void imprimir() {
***
}
}
I know that the file is on the project (I'm using netbeans)
project is on C:\NetBeansProjects\Application
file: C:\NetBeansProjects\Application\file.txt
so when I instance MiReader must be something like this:
MiReader mr = new MiReader("C:\\NetBeansProjects\\Application\\file.txt");
and now if I run the program from another location
for example now its on
D:\Pograms\Application
so the file is D:\Pograms\Application\file.txt
and now I have to change the way I create the class to
MiReader mr = new MiReader("D:\\Pograms\\Application\\file.txt");
I want to know how the program can locate the file just running the program,
something like
MiReader mr = new MiReader(program.getLocation()+"\\file.txt")
Learning english :)
You could use relative paths. Aka
MiReader Mr = new MiReader("file.text");
This way the program will look for the file file.text inside the directory you run it from.
You can use System.getProperty to get the user.home, the user.dir, the classpath etc as a standard prefix for the file you are trying to open. Here are all of the System properties
ie
File f = new File (System.getProperty("user.home" + "/foo.txt"));

Scanning file from user input

It has been a long time since I messed with files. I am trying to take a txt file I make in eclipse and use it in this code. The code to handle getting file name, finding file, and scanning it is:
System.out.println("Input from a file");
System.out.print("Enter file name: ");
String str = expression.nextLine();
int i = 0;
File file = new File(str);
Scanner fScan = new Scanner(file);
All I get are FileNotFoundExceptions. My file is in the same exact folder that all my classes for this program are in. I can't find an actual helpful answer online either .
So if someone could point out where I am going wrong that would be great :)
all of these lines of code you are having should be inside a try{} and outside have a catch, that would catch the fileNotFoundException, for example,
Try{
/*your code here*/
// but try this
Scanner scannerName = new Scanner("FileName.<extension>"); //extension being .txt, etc
String str;
while(scannerName.hasNext());{
str = scannerName.nextLine();
/*work with str here*/
}
Catch(FileNotFoundException e){
System.out.println("File not found");
}
Are you sure that the file is in the root folder ? The default working directory, is the project directory.
If you are sure that your file is there then it's either your mistaken when typing the name of your file, or somethine else is happening, to figure it out, I suggest you to try the following 3 tests :
1-make sure when you type the name of the file there is no mistake
2-Try to put the full path of the file and see if now it will find it
3-Try to put as name something like
new File("src/pa/Yourinput.txt").
If you have the file in the same package where is the class file then you can try this one also:
Scanner fScan = new Scanner(this.getClass().getResourceAsStream("abc.txt"));
//do not forget to close the Scanner in the end
fScan.close()
OR
Looking a file abc.txt from resources folder
File file = new File("resources/abc.txt");
Here is the project structure

File.createNewFile() failing in java (Ubuntu 12.04)

I am trying to createNewFile() in java.I have written down the following example.I have compiled it but am getting a run time error.
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main(String [] args)
{
try
{
File file = new File("home/karthik/newfile.txt");
if(file.createNewFile())
{
System.out.println("created new fle");
}else
{
System.out.println("could not create a new file");
}
}catch(IOException e )
{
e.printStackTrace();
}
}
}
It is compiling OK.The run time error that I am getting is
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFileExample.main(CreateFileExample.java:16)
some points here
1- as Victor said you are missing the leading slash
2- if your file is created, then every time you invoke this method "File.createNewFile()" will return false
3- your class is very platform dependent (one of the main reasons why Java is powerful programming language is that it is a NON-PLATFORM dependent), instead you can detect a relative location throw using the System.getProperties() :
// get System properties :
java.util.Properties properties = System.getProperties();
// to print all the keys in the properties map <for testing>
properties.list(System.out);
// get Operating System home directory
String home = properties.get("user.home").toString();
// get Operating System separator
String separator = properties.get("file.separator").toString();
// your directory name
String directoryName = "karthik";
// your file name
String fileName = "newfile.txt";
// create your directory Object (wont harm if it is already there ...
// just an additional object on the heap that will cost you some bytes
File dir = new File(home+separator+directoryName);
// create a new directory, will do nothing if directory exists
dir.mkdir();
// create your file Object
File file = new File(dir,fileName);
// the rest of your code
try {
if (file.createNewFile()) {
System.out.println("created new fle");
} else {
System.out.println("could not create a new file");
}
} catch (IOException e) {
e.printStackTrace();
}
this way you will create your file in any home directory on any platform, this worked for my windows operating system, and is expected to work for your Linux or Ubuntu as well
You're missing the leading slash in the file path.
Try this:
File file = new File("/home/karthik/newfile.txt");
That should work!
Actually this error comes when there is no directory "karthik" as in above example and createNewFile() is only to create file not for directory use mkdir() for directory and then createNewFile() for file.

Java and JSF, Checking if a file exists on the server

I have a web application, and I'm trying to return a boolean, of a .zip file that gets (successfully) generated on the server.
Locally I run this on Eclipse with Tomcat on Windows, but I am deploying it to a Tomcat Server on a Linux machine.
//.zip is generated successfully on the SERVER by this point
File file1 = new File("/Project/zip/theZipFile.zip");
boolean exists = file1.exists();// used to print if the file exists, returns false
if (exists)
fileLocation = "YES";
else
fileLocation = "No";
When I do this, it keeps returning false on the debugger and on my page when I print it out. I am sure it has something to do with file paths, but I am unsure.
Once I get the existence of the zip confirmed, I can easily use File.length() to get what I need.
Assume all getters and setters are in existence, and the JSF prints. It is mainly the Java backend I am having a slight issue with.
Thanks for any help! :)
Your path is not good. Try remove the leading / to fix the problem
See the test code for explanations :
import java.io.*;
public class TestFile {
public static void main(String[] args) {
try {
//Creates a myfile.txt file in the current directory
File f1 = new File("myfile.txt");
f1.createNewFile();
System.out.println(f1.exists());
//Creates a myfile.txt file in a sub-directory
File f2 = new File("subdir/myfile.txt");
f2.createNewFile();
System.out.println(f2.exists());
//Throws an IOException because of the leading /
File f3 = new File("/subdir/myfile.txt");
f3.createNewFile();
System.out.println(f3.exists());
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Debug using this statement
System.out.println("Actual file location : " + file1.getAbsolutePath());
This will tell you the absolute path of the file it's looking for

Netbeans FileReader FileNotFound Exception when the file is in folder?

so the problem is that I am having exception thrown each time I try to load the code below on NetBeans or Eclips, but when I try to run it thru TextMate everything works fine!
I tried to put the absolute address, changed the text file etc.. didn't help!
Can someone help me or tell why it won't run with IDE?
Thanks
void loadFile() {
try {
list = new LinkedList<Patient>();
FileReader read = new FileReader("a.txt");
Scanner scan = new Scanner(read);
while (scan.hasNextLine()) {
String Line = scan.nextLine();
String[] subArray = new String[5];
subArray = Line.split(",");
int a = Integer.parseInt(subArray[4]);
list.add(new Patient(Integer.parseInt(subArray[0]), subArray[1], subArray[2], subArray[3], a));
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
cap = list.size();
search_names = new int[cap];
for (int i = 0; i < list.size(); i++) {
search_names[i] = i;
}
setNames(search_names);
}//end loadFile
Debug log:
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar
Have no file for /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar
Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar
}
In netbeans the default working directory is always the root folder, i mean the folder which contains the folders which name "src", "build" etc. Place the file along with these folders and it will do the trick.
Here is step by Step procedure in NetBeans IDE 7.0.1
Click on File menu.
Click on Project Properties.
In the categories, select Run.
In main class you select your current java file.
In Arguments select the file you want to read for e.g. abc.txt or abc.java
And in Working Directory write down the path of folder in which this abc.txt or abc.java lies.
Click OK to close Project Properties.
While running your program don't forget to select your project as Main Project.
Then click F^ on keyboard. i.e. You have to raun your main project instead of just running your current java file.
That's it....enjoy!!!!
Finally found the solution
In eclipse you should put the target file in project folder. Guess same applies to NetBeans.
I had my target file in "src" folder (where the actual code files were). In fact i had to just change it to upper folder where the project folder is.
Easy and simple.
Probably you have different "working directories" in you different setups. You can check which directory you are in by printing it like this:
System.out.println(new File(".").getAbsoluteFile());
In eclipse you can set set up the working directory in the run configurations, arguments tab.
Try BufferedReader?
EDIT: Edited to show example more closely to your code. I got excepption when using File Reader. But was able to .println with BufferedReader. I did not use Scanner.
EDIT2: I was also able to get your code to work. With Scanner etc(When using full path) (Example: FileReader read = new FileReader(""C:\\myfolder\\folder\\a.txt". So hmmm.
try {
list = new LinkedList<Patient>();
BufferedReader scan = new BufferedReader(new FileReader("C:\\a.txt"));
String lines;
try {
// Scanner scan = new Scanner(read);
while ((lines = scan.readLine()) != null) {
//I just printed lines you will do your stuff here
System.out.println(lines);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "The file does not exist!" + "\nProgram is terminating.", "File Not Found", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
right click on your text file select properties and copy the path and paste it in the place where you have entered your file name
lets say you wanna add test.txt in netbeans
if your project in C:\myProject put the text file inside C:\myProject file directly not in the C:\myProject\src . then use:
File file = new File("test.txt");
Scanner in = new Scanner(file);
OR
Scanner input = new Scanner(new File("test.txt"));

Categories

Resources