How should I load files into my Java application?
Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.
FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
Since a JAVA file contains the source code for a Java application, it's easily transferable to other applications or programming languages that can understand the code or translate it to something else. For example, you can convert a JAVA file to a Kotlin file using IntelliJ IDEA.
a.We can use the Desktop class of Java to open a file in Java. This class is present in the java. awt package. It has the method open() that opens a file for us.
The short answer
Use one of these two methods:
Class.getResource(String)
Class.getResourceAsStream(String)
For example:
InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");
--
The long answer
Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:
File file = new File("C:\\Users\\Joe\\image.jpg");
This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.
Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).
Instead, use the getResource()
methods in the Class
class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.
getResource is fine, but using relative paths will work just as well too, as long as you can control where your working directory is (which you usually can).
Furthermore the platform dependence regarding the separator character can be gotten around using File.separator, File.separatorChar, or System.getProperty("file.separator").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With