Why isn't a new created file local? - java

I have the problem, that I create a new file in a Java program, but I always get an exception, that the new created file is not local, when I try to open it on the eclipse project explorer view.
The code where I create it is as follows:
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject project = workspaceRoot.getProject(projectName);
FileUtil myFile = new FileUtil();
if (!project.getFile(FILE_NAME).exists()) {
IFile newFile = project.getFile("conf.txt");
FileInputStream fileStream = null;
try {
String temp = project + "/conf.txt";
temp = temp.substring(2);
fileStream = new FileInputStream(temp);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
newFile.create(fileStream, false, null);
} catch (CoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// create closes the file stream, so no worries.
try {
myFile.writeTextFile(FILE_NAME, "Seconds", output);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
FileUtil is a class which only implements the methods write and read for the file.
The Exception I get when I try to open it begins with:
org.eclipse.core.internal.resources.ResourceException: Resource '/ProjectE1/conf.txt' is not local.
at org.eclipse.core.internal.resources.Resource.checkLocal(Resource.java:353)
at org.eclipse.core.internal.resources.File.getContentDescription(File.java:264)
at org.eclipse.core.internal.propertytester.FilePropertyTester.testContentType(FilePropertyTester.java:108)
I somehow have to get a relative path during the runtime. Because I am opening a new instance of eclipse in the program, where I can see the Project in the Project Explorer but can't open the conf.txt file because it is not local.

It looks like your resource is an absolute path to /ProjectE1/conf.txt, I'm confused why you are not using java.io.
This will help you understand relative paths, I think this may be where you are wanting to put your conf file.
File file = new File("conf.txt");
if(!file.createNewFile()){
//err
}
System.out.println(file.getAbsolutePath());

I had similar issue. This is how I fixed.
First created file in local file system (using java.io)
Did project refresh
Reload the file
File file = new File(project.getWorkspace().getRoot().getLocation() + project.getFullPath().toString() + "/relative_path_of_my_file");
file.createNewFile();
project.refreshLocal(IProject.DEPTH_INFINITE, null);
keywordFile = project.getFile("/relative_path_of_my_file");

Related

Opening file using mPdfViewer.fromFile(file) shows an empty pdf

I'm having a problem with opening file using PDFViewer library.
Inside DocumentCreator class:
1. First I create the document using iText library and it works perfectly fine and it writes document to the given directory.
2. Then I create an object of a File to display it using PDFViewer.
try {
mDocument = new Document(); // new Document created
String path = "/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "-" + recipe.getTitle() + ".pdf";
String fullPath = Environment.getExternalStorageDirectory() + "/recipes" + path;
mPdfWriter = PdfWriter.getInstance(mDocument, new FileOutputStream(fullPath));
doTheWriting(recipe, activity);
Log.d("OK", "done");
mMyRecipeFile = new File(fullPath);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside same class (DocumentCreator) I created getter method for mMyRecipeFile.
public File getRecipeFile() {
return mMyRecipeFile;
}
After that in the DocumentTestFragment,
I created PDFView, called mPdfView, and I try to open this file.
mPdfView.fromFile(mDocCreator.getRecipeFile());
The problem is it is displaying an empty document, which is weird, because I opened Android Device Monitor, opened given file and it's not empty.
I found out what caused a problem. The thing is that I wrote:
PdfView.fromFile(file)
While proper form is
PdfView.fromFile(file).load();
It works just fine now.

How to place a file for jar and read it with FileInputStream

This is the code
public static void readCharacters() {
try (FileInputStream fi = new FileInputStream("main/characters.dat"); ObjectInputStream os = new ObjectInputStream(fi)) {
characterList = (LinkedList<Character>) os.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is the structure:
And this is the Error
java.io.FileNotFoundException: main\characters.dat (The system cannot find the path specified)
What I want is to include the characters.dat file in my jar, and be able to read and write it while the program runs. Is there a different way to write the path? or to put the .dat file in a different position.
Also the writing method:
public static void writeCharacters() {
try (FileOutputStream fs = new FileOutputStream("main/characters.dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing Characters...");
os.writeObject(characterList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can't. You can do one or the other. JAR files are not file systems, and their entries are not files. You can read it with an input stream:
InputStream in = this.getClass().getResourceAsStream("/main/characters.dat");
Check it for null before proceeding.
The jar is for read-only resources. You can use it for the initial file, as a kind of template.
Path path = Paths.get(System.getProperty("user.home") + "/myapp/chars.dat");
Files.mkdirs(path.getParentPath());
if (!Files.exists()) {
try (InputStream in =
Controller.class.getResourceAsStream("/main/characters.dat")) {
Files.copy(in, path);
}
}
The above copies the initial.dat resource from the jar to the user's home "myapp" directory, which is a common solution.
System.getProperty("user.dir") would the running directory. One can also take the jar's path:
URL url = Controller.class.getResource("/main/characters.dat");
String s = url.toExternalForm(); // "jar:file:/.... /xxx.jar!/main/characters.dat"
From that you can also construct the jar's directory. Mind to check Windows, Linux, spaces and such.
URL url = Controller.class.getProtectionDomain().getCodeSource().getLocation();
The solution above risks a NullPointerException, and works a bit differenly running inside the IDE or stand-alone.
Important note:
When using getResourceAsStream, you must start your path by slash /, this specifies the root of your jar, .getResourceAsStream("/file.txt");
In my case my file was a function argument, String filename, I had to do it like this:
InputStream in = this.getClass().getResourceAsStream("/" + filename);

FileOutputStream : FileNotFoundException when attempting to instantiate

Trying to create and write to a file, but i get a FileNotFoundException every time, here is the method i am using:
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A FileNotFoundException is raised on the following line:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
The directory Exists, and a blank file is created in the target directory (visible by browsing target folder on PC).
Calling the method canWrite() on the File object returns true - i have write access.
The manifest contains: android.permission.WRITE_EXTERNAL_STORAGE"
So i'm out of ideas, i see several people have similar issues, but i cant find an answer.
Commenting out the following code fixed the issue:
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
that code does create a blank file, you can see it contained in the folder,
BUT - it's very misleading; you can't do anything with this file, i tried transferring it from my device to my PC and i couldn't, i also cannot open it. and you cannot open a stream to it in code.
Try this may helps you.
Replace this line
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
With
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), filename);

eclipse plugin how to open file in IDE by code

I am working on eclipse plugin in which i have to open a file from project explorer.
Suppose i have a project ABC in project explorer. after right click on project i got a option to run my plugin tool. after processing i got some result like Check file xyz.java.
Now i want to open this file in IDE by code
i am using this
File absolute = new File("/Decider.java");
File file = new File("/Decider.java");
IFileStore fileOnLocalDisk = EFS.getLocalFileSystem().getStore(absolute.toURI() );
FileStoreEditorInput editorInput = new FileStoreEditorInput(fileOnLocalDisk);
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
try {
page.openEditor(editorInput, "org.eclipse.ui.DefaultTextEditor");
page.openEditor(editorInput, "MyEditor.editor");
IFileStore fileStore = EFS.getLocalFileSystem().getStore(absolute.toURI() );
IDE.openEditorOnFileStore( page, fileStore );
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
IPath path = new Path(" /DirectoryReader.java");
IFile sampleFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
IEditorInput editorInput1 = new FileEditorInput(sampleFile);
IWorkbenchWindow window1=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page1 = window1.getActivePage();
try {
page1.openEditor(editorInput1, "org.eclipse.ui.DefaultTextEdtior");
} catch (PartInitException e1) {
e1.printStackTrace();
}
here it's create a new file named decider in c drive which means it's getting a wrong path.
but when i use path code in some independent java file as a normal JAVA project it's getting the correct path.
For a file in the workspace you should use IFile. If you have a selection from Project Explorer or another view that should already be an IFile or can be adapted to an IFile.
If you just have a workspace relative path use ResourcesPlugin.getWorkspace().getRoot().getFile(path) (path would include a project).
To open the default editor for the file contents use
IDE.openEditor(page, file, true);
to open a specific editor use
IDE.openEditor(page, file, "editor id");
IDE is org.eclipse.ui.ide.IDE.

Why was the file created in that path?

As a example:
public class Hello {
public static void main(String[] args) {
try {
OutputStream os = new FileOutputStream(new File("c.txt"));
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Why was c.txt generated in the root path of current project other then the same path of the java file?
thanks.
Because the root of your project is your current working directory when starting the JVM.
You can check the user.dir system property to see what is your current working directory. If you access a file without a leading slash (Unix) or drive specifier/backslash (Windows), the files will be created relative to your current working directory.
You haven't provided a full path - this means that File constructor will use your process's current directory.
The path you provided will point to the project directory only if you want to change you can
also you can mention the full path where file is to be generated.
OutputStream os = new FileOutputStream(new File("c.txt"));
OutputStream os = new FileOutputStream(new File("D:\\c.txt"));

Categories