I am new in Java and facing a problem aceessing a file. I have a package named "FileOperation" uses a "boom.txt" file(Location: "FileOperation/files/boom.txt"). What I wanted to do was to access the file from a class "MyTextPanel" (Location: "FileOperation/MyTextPanel.java").
I have created 2 methods for this purpose. One is by getClass.getResource(path) and other is by giving the absolute location of the file. Second method works, first doesn't. Someone please explain, what's the problem with the first method. Here is the class MyTextPanel:
package FileOperaton;
import java.awt.BorderLayout;
import java.io.FileReader;
import java.net.URL;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyTextPanel extends JPanel {
JTextArea textArea;
MyTextPanel()
{
setLayout(new BorderLayout());
textArea=new JTextArea();
add(textArea,BorderLayout.CENTER);
String fileName;
fileName=getFileName1();
//fileName=getFileName2();
System.out.println("File Name = "+fileName);
if(fileName!=null)
{
try {
FileReader fr=new FileReader(fileName);
System.out.println("Access Successful");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String getFileName1()
{
URL url=getClass().getResource("/files/boom.txt");
System.out.println("by getFileName1()");
if(url!=null)
return url.getFile();
return null;
}
private String getFileName2()
{
String absolutePath="E:\\Project Eclipse\\Workspace\\FileOperation\\src\\FileOperaton\\files\\boom.txt";
System.out.println("by getFileName2()");
return absolutePath;
}
}
And here are the outputs:
by getFileName1()
File Name =/E:/Project%20Eclipse/Workspace/FileOperation/bin/FileOperaton/files/boom.txt
java.io.FileNotFoundException: E:\Project%20Eclipse\Workspace\FileOperation\bin\FileOperaton\files\boom.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at FileOperaton.MyTextPanel.<init>(MyTextPanel.java:32)
at FileOperaton.MyFrame.<init>(MyFrame.java:22)
at FileOperaton.MyFrame.main(MyFrame.java:29)
by second method:
by getFileName2()
File Name = E:\Project Eclipse\Workspace\FileOperation\src\FileOperaton\files\boom.txt
Access Successful
I've also tried url=getClass().getResource("/files/boom.txt") in the first method but there url is assigned as null. And in the second method, if I use absolutePath="E:\Project Eclipse\Workspace\FileOperation\bin\FileOperaton\files\boom.txt"; (bin instead of src) it also gets success.
private String getFileName1() { URL url=getFile("/res/boom.txt"); System.out.println("by getFileName1()"); if(url!=null) return url.getFile(); return null; }
. It doesn't give success. I have also tried "res/boom.txt","/boom.txt","boom.txt","FileOperation/res/boom.txt","/FileOperation/res/boom.txt". But same result. File name is printed as null.Is this could be a compiler problem? – FRR Oct 05 '14 at 16:38