I want to read a file from directory.File is in root directory. If i use path as E:\Java\Netbeans_practice\project_141\Description.txt then it works fine.But when i wanted to use path as the file name or within a defined folder as Info\Description.txt , it gives error (java.io.FileNotFoundException: Description.txt (The system cannot find the file specified)). Actually i don't want to use the path name before project directory (ex: E:\Java\Netbeans_practice\project_141).I have searched a lot but unable to solve.Please help me. Here is my portion of code :
Scanner in = new Scanner(new FileReader("Description.txt");
while(in.hasNextLine()){
out.print("* "+in.nextLine()+"<br>");
}
When you deploy your web app, only the contents inside the "WebContent" will be deployed. You can verify this by going to (assuming you are using tomcat in your eclipse):
projectworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\<contextName>
So you may wanan copy your "Description.txt" file into "/WEB-INF" (for security sake) directory. Then you should be able to access it:
File file = new File(getServletContext().getRealPath("/WEB-INF/Description.txt"));
Update:
String path="/WEB-INF/Description.txt";
InputStream inputStream = this.getServletConfig().getServletContext().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Related
This is a chunk of data I'd like to access by a method.
I'm doing the following to read my file:
String fileName = "file.txt"
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
My file.txt is in the same package, but I still get FileNotFoundException.
I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!
This shows how to do that. https://stackoverflow.com/a/14377185/2801237
Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)
You may use:
InputStream inputStream = this.getClass().getResourceAsStream(fileName);
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I'm in troubles with opening file within my web-app. I tried it locally within Eclipse and it works fine but when I try to deploy it on Tomcat 6 on Openshift it doesn't find resource files for my web-app. There are some txt files in a ProjectFiles directory stored in WEB-INF directory; the code that locally opens file is
String nome_file = "C\:\\Users\\miKKo\\workspace\\fantacalcio_project\\WebContent\\WEB-INF\\ProjectFiles\\Risultati\\risultati_" + nome_lega + ".txt";
BufferedReader reader = new BufferedReader(new FileReader(nome_file));
I've pushed them within Git in the same repository (on server I renamed my project in "ROOT") and I've substituted string with this
String nome_file = this.getServletConfig().getServletContext().getContextPath()+"/WebContent/WEB-INF/ProjectFiles/Risultati/risultati_" + nome_lega + ".txt";
but it doesn't work. I've also tried with a context attribute
/var/lib/openshift/51c6178a5004467630000019/jbossews/work/Catalina/localhost/_/WEB-INF/ProjectFiles
but the thrown exception is always
java.io.FileNotFoundException: (#path) (No such file or directory)
What can I do for this?
Say your file is in the following location:
/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt
Then using:
String path = "/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt";
InputStream inputStream = new FileInputStream(this.getServletConfig().getServletContext().getRealPath(path));
Should work for you. Note that, ServletContext.getRealPath() return the real OS path corresponding to the given virtual path.
Edit:
If this doesn't work for your case, you really need to revisit your virtual path. You can manually check that does this file exist in the expected directory in the war file or you can log the output of the getRealPath() method to examine what's really going on! If necessary you can put "/" in your getRealPath() method and examine what is your application's root path.
Since I don't get application's root realpath, I resolved in this way:
String path="/WEB-INF/ProjectFiles/Risultati/risultati_test.txt";
InputStream inputStream = this.getServletConfig().getServletContext().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
and now it works. By the way, I also found useful informations here
getResourceAsStream() vs FileInputStream
I think I am really close, but I am unable to open a file I have called LocalNews.txt. Error says can't find file specified.
String y = "LocalNews.txt";
FileInputStream fstream = new FileInputStream(y);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Name of file is LocalNews.txt in library called News....anyone know why the file will not open?
The file is in the same Java Project that I am working on.
Error: LocalNews.txt (The system cannot find the file specified)
Project is named Bst, package is src in subPackage newsFinder, and library that the text files are stored in is called News.
Found out it was looking in
C:\EclipseIndigoWorkspace1\Bst\bin\LocalNews.txt
But I want it to look in (I believe)
C:\EclipseIndigoWorkspace1\Bst\News\LocalNews.txt
But if I make the above url a string, I get an error.
String y = "LocalNews.txt";
instead use
String y = "path from root/LocalNews.txt"; //I mean the complete path of the file
Your program can probably not find the file because it is looking in another folder.
Try using a absolute path like
String y = "c:\\temp\\LocalNews.txt";
By 'library called News' I assume you mean a jar file like News.jar which is on the classpath and contains the LocalNews.txt file you need. If this is the case, then you can get an InputStream for it by calling:
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("LocalNews.txt");
Use
System.out.println(System.getProperty("user.dir") );
to find out what your current directory is. Then you'll know for sure whether your file is in the current directory or not. If it is not, then you have to specify the path so that it looks in the right directory.
Also, try this -
File file = new File (y);
System.out.println(file.getCanonicalPath());
This will tell you the exact path of your file on the system, provided your file is in the current directory. If it does not, then you know your file is not in the current directory.
In my program (simple plain cosole app) I am reading a file a.txt.
Now I will be giving the program to someone else and he should be able to run it. I don't want the file path to be fixed like D:\a.txt , instead it should be relative to my program. Where should I place the file so that my program always finds it?
File file = new File("D:\aks.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while( (str= bufferedReader.readLine())!=null){
}
My code is working fine when I hard code the path like D:\a.txt
Put the file in the classpath (e.g. the package root or in a certain package) and just get it straight from the classpath as follows
InputStream input = getClass().getResourceAsStream("/a.txt");
// ... (continue with InputStreamReader and so on)
(the exact path depends on the location of the current class and whether you prefix with / to start from package root and which classloader you're using)
Package and distribute it as a single executabele JAR file.
See also:
Java: Pathnames not working once I export to JAR