I am making a program that opens and reads a file.
This is my code:
import java.io.*;
public class FileRead{
public static void main(String[] args){
try{
File file = new File("hello.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
but when I run, I get this error:
C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
my FileRead.java and hello.txt where in the same directory that can be found in:
C:\Users\User\Documents\Workspace\FileRead
I'm wondering what I am doing wrong?
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by #Eng.Fouad
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
In your IDE right click on the file you want to read and choose "copy path"
then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].
Related
im Working on a project that can compile/run existing java files in PC.
most of code works pretty well, but im having a problem at getting the path of java files.
here are the problematic codes
void uploadJ() {
System.out.print("Insert File name : "); //ex)HelloWorld.java
FileName = sc.next();
}
void Compile(){
String s = null;
File file = new File(FileName);
String path = file.getAbsolutePath();
try {
Process oProcess = new ProcessBuilder("javac", path).start();
BufferedReader stdError = new BufferedReader(
new InputStreamReader(oProcess.getErrorStream()));
while ((s = stdError.readLine()) != null) {
FileWriter fw = new FileWriter(E_file, true);
fw.write(s);
fw.flush();
fw.close();
}
} catch...
}
For instance, when i put HelloWorld.java as a file name,
the absolute path of the HelloWorld.java should be C:\Users\user\eclipse-
workspace\TermProject\src\HelloWorld.java,
but instead, the result is C:\Users\user\eclipse-
workspace\TermProject\HelloWorld.java.
it misses /src/ so it always ends up with javac: file not found error.
When your application has been compiled, there will be no src directory. This working directory could also be set to anything.
You also can't guarantee that the file you are looking for is an actual file, in the context of a jar file, it isn't.
However, you can load files from the classpath. You can make use of Class#getResourceAsStream(String):
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.`.
Finding the file can be accomplished by calling this.getClass().getResourceAsStream("/" + FileName), with the / causing the search to occur from the resource root.
To use this with javac, you'll have to create a temporary file and populate it with the data stream you get from getResourceAsStream.
I have a program that uses a file named list.txt to populate an ArrayList with its contents and then get a random line.
Here's the part that loads the file:
public class ReadList {
private Scanner f;
public void openFile(){
try{
f = new Scanner(new File("list.txt"));
}catch(Exception e){
System.out.println("File not found!");
}
}
However, it doesn't work when running it from a .jar file. I put the txt in the same directory and used f = new Scanner(new File("./list.txt")); yet it didn't work. I also tried some stuff I have found online but all I could manage to do is a) get a full path of the .jar with .jar included(/home/user/java/program.jar), and b) get a full path of the directory but without the / at the end(/home/user/java), which is a problem since I want this program to work on both Windows and Linux, therefore I can't simply do ("/home/user/java" + "/list.txt"), since Windows uses backslashes in paths.
So what's the simple way to just target the specific file(which will always be called list.txt) no matter which directory the file's in, as long as it's in the same place as the .jar?
Use this:
String filePath = System.getProperty("user.dir") + File.separator + "file.txt";
filePath will now contain the full path of file.txt which will be in the same dir as your jar.
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 am trying to read a file from my executable .jar file but it keeps getting null values.
I have this code:
public DanceEventTicketScanner(String txtfile){
sv = new ScannerView(this);
findcode = false;
InputStream is = this.getClass().getResourceAsStream("/resources/copy.csv");
if (is == null) JOptionPane.showMessageDialog(null, "Resource not located.");
}
In the JAR file i have (as normal) a folder containing all my .class files and in the same directory a folder named resources which holds the copy.csv file.
This code however does not recognize the file.
Does anyone have any ideas?
Remove the first slash:
InputStream is = this.getClass().getResourceAsStream("resources/copy.csv");
getClass().getResourceAsStream(..) will use a path relative to the class (so inc. package dirs). getClass().getClassLoader().getResourceAsStream(..) will use an absolute path. So change your code and get the class loader and it will work.
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.