I'm working on a very simple project that's supposed to open an image with the windows video player when run. However, I've encountered a problem. I want to have it be able to access the file "snp.jpg" with a relative file path, so it will work on computers other than my own. But, when I have it set to a absolute file path, it fails and tells me that "the file ... does not exist". Any Ideas?
import java.awt.Desktop;
import java.io.File;
public class openpic {
public static void main (String args[]) throws Exception
{
File f = new File ("C:\Users\charl\Desktop\Computer Science\JavaProjects\src\snp.png");
Desktop d = Desktop.getDesktop();
d.open(f);
System.out.println("imageviewer open;");
}
}
(Ops... fixing the answer, after I read the text above the code)
The relative path will start from the directory you run the program. Also called current working directory.
Also, as you are using Files, try to use the NIO API, with Path. Like:
Path filePath = Paths.get("./snp.png")
With this API, you can check the working directory using:
filePath.toAbsolutePath()
// just print it then, or check with a debugger
Also, be careful about the slashes.
When using Windows and this slash \, you need to make them double: \\.
Other option is to invert it: /.
Microsoft Windows syntax
import java.awt.Desktop;
import java.io.File;
public class openpic {
public static void main (String args[]) throws Exception
{
// Microsoft Windows syntax
File f = new File ("C:\\Users\\charl\\Desktop\\Computer Science\\JavaProjects\\src\\snp.png");
Desktop d = Desktop.getDesktop();
d.open(f);
System.out.println("imageviewer open;");
}
}
Related
I'm nearing the end of a program development for my computer science course. However, one of the requirements is to have a user manual within the app. I saved the user manual as a PDF inside Eclipse's workspace.
It is stored under "/Documents/PDF Manual.pdf". I originally used this code:
URL url = getClass().getResource( fileSeparator + "Documents" + fileSeparator + "PDF Manual.pdf");
//fileSeparator = '/' on mac, & '\\' on windows
File userManual = new File (url.toURI());
if (userManual.exists())
{
Desktop.getDesktop().open(userManual);
}
This works fine while running the project from eclipse, however URI returns a non hierarchical exception (as expected) when the program is exported to a jar file. I thought of playing around with url.toString(), using substring and replaceAll() to get rid of unwanted characters (%20 for the space), however this gave weird results and of course the code wouldn't work properly when it wasn't a jar file.
I looked at InputStream, however this is only used to read from a file and I cannot open the file using a desktop app.
Due to the process of submission, the pdf HAS to be saved inside the project folders.
Also, my code has to be platform independent (or at the very least, work on windows and mac) and thus manipulating file names becomes a lot more complicated. Any suggestions?
Edit:
After #SubOptimal 's help, this is the code I am now using:
String inputPdf = "Documents" + fileSeparator + "PDF Manual.pdf";
InputStream manualAsStream = getClass().getClassLoader().getResourceAsStream(inputPdf);
Path tempOutput = Files.createTempFile("TempManual", ".pdf");
tempOutput.toFile().deleteOnExit();
Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
File userManual = new File (tempOutput.toFile().getPath());
if (userManual.exists())
{
Desktop.getDesktop().open(userManual);
}
This works on mac. However, on windows manualAsStream is null for some unknown reason.
Full working example. Tested in Windows environment.
file structure
.\REPL.java
.\doc\manual.pdf
.\manifest.mf
REPL.java
package sub.optimal;
import java.io.InputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.awt.Desktop;
public class REPL {
public static void main(String[] args) throws Exception {
String inputPdf = "doc/manual.pdf";
Path tempOutput = Files.createTempFile("TempManual", ".pdf");
tempOutput.toFile().deleteOnExit();
System.out.println("tempOutput: " + tempOutput);
try (InputStream is = REPL.class.getClassLoader().getResourceAsStream(inputPdf)) {
Files.copy(is, tempOutput, StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(tempOutput.toFile());
}
}
manifest.mf
Main-Class: sub.optimal.REPL
compile
javac -d . REPL.java
create JAR
mkdir dist\
jar cvfm dist/REPL.jar MANIFEST.MF sub/optimal/REPL.class doc/manual.pdf
execute JAR
cd dist\
java -jar REPL.jar
Use getResourceAsStream instead of getResource
To write in the temp directory use createTempFile
I am trying to read a file in Java. I wrote a program and saved the file in the exact same folder as my program. Yet, I keep getting a FileNotFoundException. Here is the code:
public static void main(String[] args) throws IOException {
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
File f = new File("file.txt");
ArrayList<String> al = readFile(f, ht);
}
public static ArrayList<String> readFile(File f, Hashtable<String, Integer> ht) throws IOException{
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int ctr = 0;
}
...
return al;
}
Here is the stack trace:
Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at csfhomework3.ScramAssembler.readFile(ScramAssembler.java:26)
at csfhomework3.ScramAssembler.main(ScramAssembler.java:17)
I don't understand how the file can't be found if it's in the exact same folder as the program. I'm running the program in eclipse and I checked my run configurations for any stray arguments and there are none. Does anyone see what's wrong?
Because the File isn't where you think it is. Print the path that your program is attempting to read.
File f = new File("file.txt");
try {
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
Per the File.getCanonicalPath() javadoc, A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent.
Check the Eclipse run configuration. Look on the second tab "Arguments", at the bottom pane where it says "Working Directory". That's the place where the program gets launched and where it will expect to find the file. Usually in Eclipse it launches your program with the current working directory set to be the base project directory. If you have the java class file in a source folder and are using proper package (e.g., "com.mycompany.package"), then the data file will be in a directory like "src/com/mycompany/package" which is quite a different directory from the project directory.
HTH
File needs to be in the class path and not in the source path. Copy the file in output/class files folder and it should be available.
You should probably check out this question: Java can't find file when running through Eclipse
Basically you need to be sure where the execution is taking place (current directory) and how your SO will resolve the relative paths. Try changing the working directory in Eclipse' Run Configurations>Arguments or provide the absolute filename
I'm extremely late to responding to this question, but I see that this is still an extremely hot topic to this day. It may not seem obvious, but what you want to use here is actually the newer file-handling i/o library, java.nio. The below explained example shows how to read a String from a file path, but I encourage you to take a look at the docs if you have a different use.
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Files;
public static void main(String[] args) throws IOException {
Path path = Path.of("app/src/main/java/pkgname/file.txt");
String content = Files.readString(path);
System.out.println(content); // Prints file content
}
Okay, code done, now time for the explanation. I'll start off with the import statements. java.io.IOException is necessary for some exception-handling. (Sidenote: Do not omit the throws IOException and/or the IOException import. Otherwise Files.readString() may throw an error in your editor, which I'll get to shortly). The Path class import is necessary to actually get the file, and the Files class import is necessary for file operations.
Now, the main function itself. The first line receives a Path object representing a file for you to actually read/write. Here the question of path name arises, which is the basis of the question. I have seen other solutions that tell you to take the absolute path of your file, but don't do that! It's extremely bad practice, especially with open-source or public code. Path.of actually allows you to use the path relative to your root folder (unless it isn't in a directory, simply inputting the file name does not work, I'm afraid). The example path name I gave is an example of a Gradle project. Next line, we get the content of the file as a String using a method from Files. Again, if you have a different use for a file, you can check the docs (a different method from the Files class will probably work for you). On the final line, we print the result. Hooray! Our output is just what we needed.
There you have it, using Path instead of File is the solution to this annoying bug. Hopefully this helps!
I have created a java program in eclipse and I am now ready to export it as a jar. My program uses an image file and an executable file. When testing my program in eclipse I referred to these file with a full path, which I obviously cannot do for the jar. Therefore, I changed them like this:
public static final String DRIVERLOC = "./resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
and
File pic = new File("./images/Open16.gif");
openButton = new JButton("Select the Text File", createImageIcon(pic.getAbsolutePath()));
I put the images and the resources and images directory in the same directory with the jar. Now for some reason when I run the jar the IEDriverServer works fine but the image does not work and the error is that it cannot find the image. I am confused since I cannot seems to tell the difference. I also used "images/Open16.gif" which did not work either. Why would one work but the other does not? What is the easiest way to fix this?
We do this exact same thing with Selenium Drivers.
What you need to do is take the executable file out of the jar and put it some where windows can run it. If you try and open a jar/zip in Windows Explorer and then double click the .exe inside of a jar/zip, windows will extract the file to a temp directory, and then run it. So do the same thing:
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TestClass {
public static void main (String[] args) throws IOException {
InputStream exeInputStream = TestClass.class.getClassLoader().getResourceAsStream("resources/IEDriverServer.exe");
File tempFile = new File("./temp/IEDriverServer.exe");
OutputStream exeOutputStream = new FileOutputStream(tempFile);
IOUtils.copy(exeInputStream, exeOutputStream);
// ./temp/IEDriverServer.exe will be a usable file now.
System.setProperty("webdriver.ie.driver", tempFile.getAbsolutePath());
}
}
Let's say you save the jar and make it run this main function by default.
Running C:\code\> java -jar TestClass.jar Will run the jar from the C:\code directory. It will create the executable at C:\code\temp\IEDriverServer.exe
With your path set to "./resources/IEDriverServer.exe" you are referring to a file on the hard drive "." which does not exist.
You need to get the path of your .jar-file.
You can do this by using
System.getProperty("java.class.path")
This can return multiple values, seperated by semi-colons. The first one should be the folder your jar is in.
You can also use
<AnyClass>.class.getProtectionDomain().getCodeSource().getLocation()
I hope this helps :)
EDIT:
// First, retrieve the java.class.path property. It returns the location of all jars /
// folders (the one that contains your jar and the location of all dependencies)
// In my test it returend a string with several locations split by a semi-colon, so we
// split it and only take the first argument
String jarLocation = System.getProperty("java.class.path").split(";")[0];
// Then we want to add that path to your ressource location
public static final String DRIVERLOC = jarLocation + "/resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
You can read about this here.
Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
String sourceDirectory = "~/Documents";
System.out.println(sourceDirectory);
File dir = new File(sourceDirectory);
File[] dirFiles = dir.listFiles();
for (File file : dirFiles)
{
System.out.println( file.getName() );
}
}
}
I am using the code above to list files in the Documents directory in Ubuntu. The same code works if I replace the folder name to a local folder where the Java class file resides. HOwever, I always get NULL Pointer exception when using absolute paths, as the dirFiles is NULL.
Could someone explain if there is any mistake in my approach.
Thanks.
Tilda ~ is not absolute path. It is a feature of typical unix shell to replace it by home directory of current user. In java program you should use System.getProperty ("user.home") instead of tilda.
The problem seems to be with the sourceDirectory. Instead of ~/Documents , try with the complete path /home/foo/Documents