How can I access the CD Rom drive (in my case, F:) from Java? I don't mind platform specific code. I am using Windows 8. I have the following code but get AccessDenied.
public static void main(String args[]) throws IOException {
File cd = new File( "f:\\lang" );
System.out.println(cd.canRead());
RandomAccessFile rawAccess = new RandomAccessFile( cd, "r" );
rawAccess.close();
}
The 3 trues are checking for cd.canRead, cd.canWrite, cd.canExecute.
true
true
true
Exception in thread "main" java.io.FileNotFoundException: f:\lang (Access is denied) at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(Unknown Source) at myapp.main(myapp.java:16)
RandomAccessFile provides access to Files not Directories.
The FileNotFound is thrown, because there is no file, just a directory.
http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html#RandomAccessFile(java.io.File, java.lang.String)
I see my error now. I'm trying to use the Java File object when what I really want is raw data from the disc. I was giving a directory and trying to open it like a file causing the error seen in the original post. It worked once I changed the path to a specific file.
I will create a new question that is more clear about what I want. Thank you.
Related
Code:
import java.io.*;
import java.util.Scanner;
public class Driver {
private int colorStrength;
private String color;
public static void main(String[] args) throws IOException {
String line, file = "strength.txt";
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);
while (inFile.hasNext()) {
line = inFile.nextLine();
System.out.println(line);
}
inFile.close();
}
}
This is a small part of a program I am writing for a class (the two private attributes have yet to be used I know) but when I try to run this with the strength.txt file I receive the following errors:
Exception:
Exception in thread "main" java.io.FileNotFoundException: strength.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Driver.main(Driver.java:14)
If anyone with Eclipse could help me figure this out it would be much appreciated!
You've used a relative file path which is relative to your project execution.
If you'd like to do it that way, simply put the strength.txt file in the base directory of your project. Like so:
Alternatively, you could reference the absolute file path on your system. For example, use:
Windows:
C:/dev/myproject/strength.txt
Mac/Unix:
/Users/username/dev/strength.txt
(or whatever the full path may be) instead.
Do this
System.out.println(openFile.getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well, Accordingly place the file or give the exact location
Use this to see what file path the system is using to reach the relative path
System.out.print(System.getProperty("user.dir"));
Then make sure that the relative path immediately follows this path.
You can also turn that into a string by doing
String filePath = System.getProperty("user.dir");
and then you can just add that to the beginning of the filepath like so,
ImageIcon imageIconRefVar = new ImageIcon(filePath + "/imagepathname");
I found this solved the issue for me when I used it in the path (which seemed odd since that should be the location it is in, but it worked)
You've used a relative file path which is relative to your project execution.
If this works for you, you can change the execution directory from the project root to the binary directory by:
"Run" -> "Run configurations"
In the "Arguments" tab, find "working directory" settings.
Switch from "Default" to "Other".
Click the "Workspace" button and select the project in pop-up window then click "OK"; this will bring you something like $(workspace_loc:proj-1).
Append "/bin" to the end of it; save the configuration.
I need this instead of simply putting files in project root directory when I am doing assignment and the professor requires specific file hierarchy; in addition, this is more portable than absolute path.
Inside the base directory create a folder, name it "res". Place your file inside "res" folder.
use String file = ".\\res\\strength.txt"; to reference the location of your file.
You should use a resource folder to store all the files you use in your program (a good practice).
And make a refrence of that file from your root directory. So the file is present within the package.
This code throws FileNotFoundException.
Edit: As requested I have included the full StackTrace.
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadFile{
public static void main(String[] args){
InputStream inputstream = new FileInputStream("C:\\file.txt");
}
}
The file "file.txt" is at that location though. I would like to post a screenshot of this as requested, but I can't because I need at least 10 reputation points.
If you are 100% certain that the file exists and you're still getting a FileNotFoundException, than most likely your user or the user running Java has no permission to access this file (since I am using German Windows the dialog is in German, but as you can see "Benutzer" (which is Users) have a denied right to read and execute the file a.txt:
This however, results in a a FileNotFoundException with a localized error message returned :
Exception in thread "main" java.io.FileNotFoundException: C:\a.txt (Zugriff verweigert)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at java.io.FileInputStream.<init>(FileInputStream.java:87)
at Threadstuff.main(Threadstuff.java:50)
Zugriff verweigert means "access denied". If that isn't the problem either, I guess you should post your full StackTrace.
The other option I mentioned in my comment is an explorer option ("View" -> "Options") in the Folder and Search options -> View:
(roughly translates to "Hide extensions for known extensions")
If this is enabled, the filenames in the explorer are losing their extensions in the view. Meaning that they are shown as "file" instead of "file.txt" - which sometimes leads to the mistake of creating a "file.txt.txt" when renaming a file. And is/was also often used to trick users into thinking they were open a different kind of file (.pdf.exe) - mostly used by bad guys.
Is this really the full Filepath? Better check that one.
Also I'd recommend putting files that are to be read by your program e.g. Textfiles, Images and such into the classpath of your project so when you pack and export it the file paths are not obstructed by being on somebody else's PC where that file does not exist on that path and so on.
This answer suggest you transform the Path of the file to a java conform URL path.
Try the below one.
InputStream inputstream = new FileInputStream("C:"+File.separator+"file.txt");
A better approach would be
File file = new File("C:"+File.separator+"file.txt");
if(file.exists()) {
//Read the file
}
else {
System.out.println("File does not exist);
}
To ensure whether file exists or not in windows, press windows button + r and then paste the file path you have mentioned and after that press enter key. If file is in that location, a notepad with file contents will be opened.
As part of a jar ran through hadoop, I want to implement a simple function that (a) creates a file if it doesn't exist, (b) appends bytes from a string passed in on a new line into this file.
I wrote the following:
public class FSFacade {
private static FileContext fc = FileCOntext.getFileContext();
public static void appendRawText(Path p, String data) throws IOException {
InputStream is
= new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
FsPermission permissions
= new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL);
OutputStream os
= fc.create(p,
EnumSet.of(CREATE, APPEND),
CreateOpts.perms(permissions),
CreateOpts.createParents());
IOUtils.copyBytes(is, os, new Configuration());
}
}
This code works fine in Eclipse, but when I try and run it on an HDFS via hadoop jar it raises either of the following exceptions:
java.io.FileNotFoundException: /out (Permission denied)
java.io.FileNotFoundException: /results/out (no such file or directory)
I assume the first one is raised because my process doesn't have permissions to write to the root of the HDFS. The second one probably means my code somehow doesn't create the file if it doesn't exist yet.
How can I make sure, programatically, that my process
(a) has all the appropriate permissions to write into the Path passed in ? (I presume it means execute perms on all folders in the path and write perms on the last one ?)
(b) indeed creates the file if it doesn't exist yet, as I expected EnumSet.of(CREATE, APPEND) to do ?
You can use the following command to give permission to write into HDFS
> hdfs dfs -chmod -R 777 /*
* means permissions will be enabled for all folders
777 will enable all permissions (read , write and execute)
Hope it helps !!
this is my first time posting on stackoverflow. I have a question about a series of errors that I have been encountering when I try to read in data from a generic text file in Netbeans IDE 7.4. I am using a 2009 iMac with Mac OS X Mavericks.
import java.util.Scanner;
import java.io.File;
public class two {
public static void main(String[] args) throws Exception
{
System.out.println("Directory: "+System.getProperty("user.dir"));
File f = new File("newfile.dat");
Scanner s = new Scanner(f);
}
}
And this code will return this set of errors:
Directory: /Users/omavine/Desktop/aPlusComputerScience
Exception in thread "main" java.io.FileNotFoundException: newfile.dat (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:143)
at java.util.Scanner.<init>(Scanner.java:656)
at apluscomputerscience.two.main(two.java:22)
at apluscomputerscience.APlusComputerScience.main(APlusComputerScience.java:21)
Java Result: 1
This would indicate to me that the file simply was not being searched for in the correct path, however, when I compare the filename with the absolute path:
System.out.println("Directory: "+System.getProperty("user.dir"));
File f = new File("newfile.dat");
System.out.println("Path: "+f.getAbsolutePath());
Then the output is as follows:
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/omavine/Desktop/aPlusComputerScience/newfile.dat
Which would indicate (to me) that the file is being searched for in the correct place whether I look for it with the explicit pathname or not.
However, when I try to construct the Scanner, (even with the absolute pathname):
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/maven/Desktop/aPlusComputerScience/newfile.dat
Exception in thread "main" java.io.FileNotFoundException: /Users/omavine/Desktop/aPlusComputerScience/newfile.dat (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:143)
at java.util.Scanner.<init>(Scanner.java:656)
at apluscomputerscience.two.main(two.java:23)
at apluscomputerscience.APlusComputerScience.main(APlusComputerScience.java:21)
Java Result: 1
Still the same error. Interestingly enough, attempting to construct the scanner by using:
File f = new File("newfile.dat");
Scanner s = new Scanner(f.getClass().getResourceAsStream("newfile.dat"));
Returns:
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/omavine/Desktop/aPlusComputerScience/newfile.dat
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at java.util.Scanner.<init>(Scanner.java:608)
at apluscomputerscience.two.main(two.java:23)
at apluscomputerscience.APlusComputerScience.main(APlusComputerScience.java:21)
Java Result: 1
(Reading in the file with the getClass().getResourceAsStream() seems to return a null pointer exception, for whatever reason.)
I'd like to be able to read files on my home computer. This type of scenario has never happened to me at other computers with JCreator IDE. Can anyone make heads or tails of this dilemma?
the output clearly indicates you are looking at different directories.
Directory: /Users/omavine/Desktop/aPlusComputerScience
Path: /Users/maven/Desktop/aPlusComputerScience/newfile.dat
the working directory is in omavine's desktop. your file is in maven's desktop.
Instead of giving the relative path, try giving the actual path of the file.
File f = new File("/Users/maven/Desktop/aPlusComputerScience/newfile.dat");
this ought to work.
EDIT: about the NullPointerException for getResourceAsStream
the java API doc statest that
Returns:
An input stream for reading the resource, or null if the resource could not be found
and the Scanner throws the NullPointerException.
refer javadocs
I have a program that scans a file and then closes the file.
import java.util.*;
import java.io.*;
public class FileTester{
public static void main(String[] args) throws IOException {
File test = new File("MyDatta.in.txt");
Scanner sf = new Scanner(test);
sf.close();
}
}
When I run the program I get an error message like this:
Exception in thread "main" java.io.FileNotFoundException: MyDatta.in.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at FileTester.main(FileTester.java:6)
I have a mac that runs on Mac OS. I have reason to believe it has to do with the pathway to my file which is in documents. I know in windows one would use C:\folder name\file to scan it but I just don't know with Mac and I cannot find it anywhere
From Java documentation for FileInputStream: "If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown."
Maybe file is used by another program?
You should put this as the file path:
~/Documents/MyDatta.in.txt
to tell java that your file is in documents. The ~ is your home folder.