The system cannot find the path specified - text file - java

I added a text file to my project as in this path:
Myproject/WebPages/stopwords.txt
Image:
http://s7.postimg.org/w65vc3lx7/Untitled.png
I tried to open the file, but i can't !
My code:
BufferedReader br = new BufferedReader(new FileReader("stopwords.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
Error:
stopwords.txt (The system cannot find the path specified)

You can try something like,
I guess that you are in .jsp file.
<%
String path = request.getServletContext().getRealPath("/WebContent/stopwords.txt") ;
BufferedReader br = new BufferedReader(new FileReader(path));
// other codes...
%>
EDITED :
<%
String path = request.getServletContext().getRealPath("/stopwords.txt") ;
//check here with print path variable...
// you can pass this path variable to invoke method which is reside into //your java class...
BufferedReader br = new BufferedReader(new FileReader(path));
%>

The FileReader will be opening the file relative to the path this is executed from. If this is being executed from the "MyProject" folder, you will need to specify the folder in the FileReader constructor as in FileReader("WebPages/stopWords.txt")

If your projectpath is the root folder. Where the class is isn't where the root folder is. Changing it to this should work. You also need to add a space to your filename.
BufferedReader br = new BufferedReader(new FileReader("/Web Pages/stopwords.txt"));

empirical method:
begin to create and write some file => then you will see where it is on the filesystem
then place you file in the same directory, and retry others methods to read it
warning: sometimes, you cant read or write in some directories.

Related

Java FileReader Error: file not found

Iam trying to add a path (string) over an editfield in class main, the path will be taken to another class extract. After this I want to read the file with FileReader, but I got some error: file not found.
So I does some test:
I wrote the path directly in the FileReader -> everything Okay
I wrote a function File named sFile to get the path from class main and try to find the file behinde the path (exists). The file could be found but if FileReader trying to load the file got the same error
Code:
File sFile = new File(path);
if (sFile.exists()){
System.out.println("Found.");
System.out.println(sFile.getAbsolutePath());
try{
FileReader file = new FileReader(sFile); //db10916358-hp.sql (test file)
String[] fReadTmp = new String[10240000];//Just for testing
BufferedReader br = new BufferedReader(file);
String read = br.readLine();//Read a line
I found the error, it was an other File function which creates some files from the extract.
It was so simple, sorry for that.
Thanks for your time!
Try this snippet of code its work correctly
public static void readFile(String path) throws FileNotFoundException, IOException{
File file = new File(path);
if(file.exists())
{
FileReader fileReader = new FileReader(file); //db10916358-hp.sql (test file)
BufferedReader br = new BufferedReader(fileReader);
String read = br.readLine();//Read a line
}
else
{
System.out.print("Not Found");
}
}

program does not work properly when moved to Servlet

I have made a program that works perfectly well in java class.. but when I moved my code to a servlet it does not work as expected
the program creates some files writes to them then later reads from them.. the problem is when I move the code to servlet the program would not create files in the first place, so when later reading them it will give FileNotFound exception
this is how I create write to and read from files.
first, create file and write to it
...
Writer output = null;
File file = new File(i + ".txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
... then later read from file
File file = new File(i+".txt");
Scanner br = new Scanner(file);
// BufferedReader br = new BufferedReader(new FileReader(new File(TDM.class.getResource(i + ".txt").getPath())));
while (br.hasNextLine()) {
line = br.nextLine();
...
Notes:
*the above code is NOT in servlet.. servlet only CALL the method that contains this code.
*apparently, the PROBLEM is with creating the file.. for some reason the file is not created when the method is called from servlet. how ever it works perfectly when called from another java class.
thanks in advance
Use a path: File.createTempFile for temporary files, or convert a web path ("/.../...") relative to your web contents into a file system File:
File file =
request.getServletContext().getRealPath("/WEB-INF/files/" + i + ".txt");
file.getParentFile().mkdirs();
...
Better yet give URLs to a file, that will be delivered by a Servlet streaming the file to
response.setContentType("text/plain");
response.getOutputStream();
...
If you write resource "files," that may reside in a .war of .jar; then do not use File.
Read them using an InputStream:
InputStream in = getClass().getResource("/...").getResourceAsStream();
And copy them to the response.getOutputStream().
Also do not use the utility "short-hand" class FileWriter as it uses the platform encoding, which on Windows is some ANSI encoding and on Linux servers in general is UTF-8.
new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(file), "UTF-8"));
this comment from "Elliott Frisch" solved my problem
"You need to specify a path to your files."
simply I had to provide the "absolute" path instead of relative path
so, the code should be like this
Writer output = null;
File file = new File("/file/path/"i + ".txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
and
File file = new File("/file/path/"i+".txt");
Scanner br = new Scanner(file);
// BufferedReader br = new BufferedReader(new FileReader(new File(TDM.class.getResource(i + ".txt").getPath())));
while (br.hasNextLine()) {
line = br.nextLine();
then when I had this exception java.lang.NoClassDefFoundError: org/jsoup/Jsoup I just had to downlad the jsoup library from the internet and add it to my project under (library folder).
thank you very much for you all :)

Examining file structure in application jar

I have a directory in my jar called "lessons". Inside this directory there are x number of lesson text files. I want to loop through all these lessons read their data.
I of course know how to read a file with an exact path:
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/lesson1.lsn")));
try{
in.readLine();
}catch(IOException e){
e.printStackTrace();
}
But what I want is something more like this:
File f = new File(Main.class.getResource("lessons"));
String fnames[] = f.list();
for(String fname : fnames){
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/" + fname)));
in.readLine();
}
File however doesn't take a URL in it's constructor, so that code doesn't work.
I will use junit.jar in my test as an example
String url = Test1.class.getResource("/org/junit").toString();
produces
jar:file:/D:/repository/junit/junit/4.11/junit-4.11.jar!/org/junit
lets extract jar path
String path = url.replaceAll("jar:file:/(.*)!.*", "$1");
it is
D:/repository/junit/junit/4.11/junit-4.11.jar
now we can open it as JarFile and read it
JarFile jarFile = new JarFile(path);
...

Where to put a file to read from a class under a package in java?

I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}

Java, reading a file from current directory?

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me

Categories