How to open java file
How to open java file
What Is a JAVA File?
How to open, edit, & convert JAVA files
What to Know
This article explains what a JAVA file is and how to open one on your computer, or convert one to a KT, JAVA, or EXE file.
What Is a JAVA File?
A JAVA file is used by a Java compiler to create a Java class files (.CLASS), which is usually a binary file and not human-readable. If the source code file contains multiple classes, each one is compiled into its own CLASS file.
It’s the CLASS file that’s then turned into an executable app with the JAR file extension. These Java archives make it easier to store and distribute CLASS files and other application resources like images and sounds.
How to Open JAVA Files
Chances are slim that you have a program on your computer that will open a JAVA file when double-clicked. Otherwise, use one of the programs below by first opening the software and then using a File or Import menu to browse for the file.
The text within a JAVA file can be read by any text editor, like Notepad in Windows, TextEdit in macOS, etc.
However, JAVA files are only actually useful when they’re compiled into a bytecode CLASS file, which a Java SDK can do. Data within the CLASS file is used by Oracle’s Java Virtual Machine (JVM) once the JAR file has been created.
Use the following command in Command Prompt to open the JAVA file in the Java SDK, which will make a CLASS file. Be sure to, of course, change the text within the quotes to be the path to your file.
This command only works if you have the javac.exe file on your computer, which comes with the Java SDK installation. This file is stored in the bin folder of the C:\Program Files\jdk(version)\ directory. The easiest way to use the command is to set this location as a PATH environment variable.
To edit JAVA files, use a program intended for application development, like Eclipse or JCreator LE. Text editors like NetBeans and those in the link above can also be useful.
How to Convert a JAVA File
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. Either use the Code menu item to find the Convert Java file to Kotlin File option or access the Help > Find Action menu and start typing the action you want to complete, like convert java file. It should save the JAVA file to a KT file.
Use the javac command mentioned above to convert JAVA to CLASS. If you can’t seem to invoke the tool from Command Prompt, one CMD trick you can do is access the EXE file’s location as described above, and then drag and drop the javac.exe file directly into Command Prompt to complete the command.
Once the file is in the CLASS format, you can essentially convert JAVA to JAR using the jar command, as described in this Java tutorial from Oracle. It will make a JAR file using the CLASS file.
JSmooth and JexePack are two tools that can be used to convert JAVA to EXE so that the app can run like a normal Windows executable file.
Still Can’t Open It?
The first thing you should do if the file isn’t opening or converting with the tools described above is double-check the extension. It’s possible you’re not actually dealing with a JAVA file, but instead a file that uses a similarly spelled file extension.
For example, the AVA suffix looks a bit like JAVA, but it’s used for AvaaBook eBook files. If you’re dealing with an AVA file, it won’t open with the programs from above, but instead only works with Persian AvaaPlayer.
JA files are similar; these are Jet Archive files that store compressed game files. Another is JavaScript Proxy Autoconfig files (.JVS) that web browsers use to configure a proxy server.
You can read a file, such as a CSV file, in Java using the BufferedReader class method. Visit Oracle’s documentation to learn more about the BufferedReader class and other methods for reading files, such as FileReader, InputStreamReader, and Files.newBufferedReader( ).
There are several options for creating files in Java. One method is the createNewFile( ) method to open a blank file. Dive deeper with Oracle’s tutorial about creating files in Java.
How to Read a File in Java
Last modified: March 11, 2022
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this tutorial, we’ll explore different ways to read from a File in Java.
First, we’ll learn how to load a file from the classpath, a URL, or from a JAR file using standard Java classes.
Second, we’ll see how to read the content with BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, and FileChannel. We will also discuss how to read a UTF-8 encoded file.
Finally, we’ll explore the new techniques to load and read a file in Java 7 and Java 8.
This article is part of the “Java – Back to Basic” series on Baeldung.
Further reading:
Java – Create a File
Java – Write to File
2. Setup
2.1. Input File
In most examples throughout this article, we’ll read a text file with filename fileTest.txt that contains one line:
For a few examples, we’ll use a different file; in these cases, we’ll mention the file and its contents explicitly.
2.2. Helper Method
We’ll use a set of test examples with core Java classes only, and in the tests, we’ll use assertions with Hamcrest matchers.
Tests will share a common readFromInputStream method that transforms an InputStream to String for easier asserting of results:
Note that there are other ways of achieving this same result. We can consult this article for some alternatives.
3. Reading a File from the Classpath
3.1. Using Standard Java
This section explains how to read a file that is available on a classpath. We’ll read the “ fileTest.txt ” available under src/main/resources :
In the above code snippet, we used the current class to load a file using getResourceAsStream method and passed the absolute path of the file to load.
The same method is available on a ClassLoader instance as well:
The main difference is that when using the getResourceAsStream on a ClassLoader instance, the path is treated as absolute starting from the root of the classpath.
When used against a Class instance , the path could be relative to the package, or an absolute path, which is hinted by the leading slash.
Of course, note that in practice, open streams should always be closed, such as the InputStream in our example:
3.2. Using the commons-io Library
Another common option is using the FileUtils class of the commons-io package:
Here we pass the File object to the method readFileToString() of FileUtils class. This utility class manages to load the content without the necessity of writing any boilerplate code to create an InputStream instance and read data.
The same library also offers the IOUtils class:
Here we pass the FileInputStream object to the method toString() of IOUtils class. This utility class acts in the same way as the previous one in order to create an InputStream instance and read data.
4. Reading with BufferedReader
Now let’s focus on different ways to parse the content of a file.
We’ll start with a simple way to read from a file using BufferedReader:
Note that readLine() will return null when the end of the file is reached.
5. Reading from a File Using Java NIO
In JDK7, the NIO package was significantly updated.
Let’s look at an example using the Files class and the readAllLines method. The readAllLines method accepts a Path.
Path class can be considered an upgrade of the java.io.File with some additional operations in place.
5.1. Reading a Small File
The following code shows how to read a small file using the new Files class:
Note that we can use the readAllBytes() method as well if we need binary data.
5.2. Reading a Large File
If we want to read a large file with Files class, we can use the BufferedReader.
The following code reads the file using the new Files class and BufferedReader:
5.3. Reading a File Using Files.lines()
JDK8 offers the lines() method inside the Files class. It returns a Stream of String elements.
Let’s look at an example of how to read data into bytes and decode it using UTF-8 charset.
The following code reads the file using the new Files.lines():
Using Stream with IO channels like file operations, we need to close the stream explicitly using the close() method.
As we can see, the Files API offers another easy way to read the file contents into a String.
In the next sections, we’ll look at other less common methods of reading a file that may be appropriate in some situations.
6. Reading with Scanner
Next let’s use a Scanner to read from the File. Here we’ll use whitespace as the delimiter:
Note that the default delimiter is the whitespace, but multiple delimiters can be used with a Scanner.
The Scanner class is useful when reading content from the console, or when the content contains primitive values, with a known delimiter (eg: a list of integers separated by space).
7. Reading with StreamTokenizer
Now let’s read a text file into tokens using a StreamTokenizer.
The tokenizer works by first figuring out what the next token is, String or number. We do that by looking at the tokenizer.ttype field.
Then we’ll read the actual token based on this type:
In this example, we’ll use a different input file which simply contains:
The following code reads from the file both the String and the number:
Note how the end of file token is used at the end.
This approach is useful for parsing an input stream into tokens.
8. Reading with DataInputStream
We can use DataInputStream to read binary or primitive data types from a file.
The following test reads the file using a DataInputStream:
9. Reading with FileChannel
If we are reading a large file, FileChannel can be faster than standard IO.
The following code reads data bytes from the file using FileChannel and RandomAccessFile:
10. Reading a UTF-8 Encoded File
Now let’s see how to read a UTF-8 encoded file using BufferedReader. In this example, we’ll read a file that contains Chinese characters:
11. Reading Content from URL
To read content from a URL, we will use “/” URL in our example:
There are also alternative ways of connecting to a URL. Here we used the URL and URLConnection class available in the standard SDK.
12. Reading a File from a JAR
To read a file which is located inside a JAR file, we will need a JAR with a file inside it. For our example, we will read “LICENSE.txt” from the “hamcrest-library-1.3.jar” file:
Here we want to load LICENSE.txt that resides in Hamcrest library, so we will use the Matcher’s class that helps to get a resource. The same file can be loaded using the classloader too.
13. Conclusion
As we can see, there are many possibilities for loading a file and reading data from it using plain Java.
We can load a file from various locations like classpath, URL, or jar files.
Then we can use BufferedReader to read line by line, Scanner to read using different delimiters, StreamTokenizer to read a file into tokens, DataInputStream to read binary data and primitive data types, SequenceInput Stream to link multiple files into one stream, FileChannel to read faster from large files, etc.
how to open a jar file in Eclipse
I downloaded a demo jar file, and would like to open it in eclipse. What I did is
However, the eclipse returns «No projects are found to import».
As command line, I type
This jar file just functions well. So it seems to me that jar file itself is OK, but how can I open it in Eclipse and modify this demo code? Thanks.
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
use java decompiler. http://jd.benow.ca/. you can open the jar files.
A project is not exactly the same thing as an executable jar file.
For starters, a project generally contains source code, while an executable jar file generally doesn’t. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.
Then import it into Eclipse.
Firstly, it’s necessary to know what is a jar file.
JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time.
Above command returns:
‘java’ is not recognized as an internal or external command, operable program or batch file.
Is there a way I can still open/run this?
e: OS is Windows 8.
15 Answers 15
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
you can use the command prompt:
Hope it works for you.
There are two different types of Java to download: The JDK, which is used to write Java programs, and the RE (runtime environment), which is used to actually run Java programs. Are you sure that you installed the RE instead of the SDK?
Use cmd prompt and type
To run your jar file.
for more information refer to this link it describes how to properly open the jar file. https://superuser.com/questions/745112/how-do-i-run-a-jar-file-without-installing-java
It is not a good idea (sometimes annoying) to change the registry key every time I want to run an app build from a different version.
Scenario:
Multiple JDKs (1.7, 1.8, 9.0, 10.0, 11.0, and 12.0)are installed in the PC, so the latest installed was 12.0.
Problem
This is my work around solution:
Change the text in the target (for example «D:\Dev\JavaApp1.8.jar» ) To
How To Work With Files In Java
You can use this guide to learn how to work with files in Java through the Path API. From reading and writing files, to watching directories & using in-memory file systems.
Java’s File APIs
Java has two file APIs.
The original java.io.File API, available since Java 1.0 (1996).
The newer java.nio.file.Path API, available since Java 1.7 (2011).
What is the difference between the File and Path APIs?
The old file API is used in a ton of older projects, frameworks and libraries. Despite its age, it is not deprecated (and likely never will be) and you can still use it with any of the latest Java versions.
Nevertheless, java.nio.file.Path does everything java.io.File can, but generally in a better way and more. A few examples:
File Features: The new classes support symlinks, proper file attributes and metadata support (think: PosixFileAttributes), ACLs and more.
Decoupling: Enabling support for in-memory file systems, which we’ll cover later.
(For a full list of differences between the two APIs, check out this article: https://www.oracle.com/technical-resources/articles/javase/nio.html)
Which file API should I use?
For the reasons mentioned above, if you are starting a new Java project, it is highly recommended to use the Paths API over the File API. (Even though file reads so much nicer than path, doesn’t it?)
Hence, we will focus solely on the Paths API in this article.
Paths API
To work with files in Java, you first need a reference to a file (big surprise!). As we just mentioned above, starting with Java 7, you would use the Paths API to reference files, so it all starts with constructing Path objects.
Let’s see some code.
Let’s break this down:
Starting with Java 11, you should use the static Path.of method to construct paths (we’ll cover the Java7-10 equivalent in a second).
It does not matter if you are using forward slashes e.g. on Windows, as the Path API is smart enough to construct the right path, independently of the OS and any forward-backward slash issues.
So, both lines above will return the following result, when running the main method.
There are more choices you have when constructing paths: You don’t have to specify the complete path as one long string:
Instead, you can pass a sequence of strings to the Path.of method, or construct the parent directory and use it to get a child file ( .resolve(child) ).
Again, the output will be the same as before.
Last but not least, you can also pass URIs into the Path.of call.
It sounds like a broken record, but the output….will be the same.
So, you have a variety of choices constructing your Path objects.
Two important points, however:
Constructing a path object or resolving a child, does not mean the file or directory actually exists. The path is merely a reference to a potential file. So, you’ll have to separately verify its existence.
Once you have a path object, you can finally do something with it. Let’s see what and how in the next section.
Common File Operations
When working with files or paths, you will likely be using the java.nio.file.Files class. It contains a ton of common & useful static methods, that operate on files and directories.
Use this section as a quick cheat sheet, the headings are self-explanatory.
How to check if a file exists
Checks if a file or directory exists. Also lets you specify additional parameters, to define how symlinks are handled, i.e. followed (default) or not.
When running this snippet, you’ll get a simple boolean flag back.
How to get the last modified date of a file
Self-explanatory. Returns the last date your file was modified as a FileTime object.
How to compare files (Java12+)
Hence, if you are comparing two completely different files, you’ll get this as console output: the very first byte already didn’t match, hence the mismatch is position zero.
How to get the owner of a file
How to create temp files
Let’s break this down.
When creating temp files, you can specify a prefix (first param) and a suffix (second param). Both can be null.
The prefix will be prefixed (duh!) to the temp file name, the suffix is essentially the file extension, and if you leave it out a default extension of «.tmp» will be used.
Instead of the default temp directory, you can also specify your own directory where you want the temp file to be created.
In addition to files, you can also create temp directories. As you don’t need the suffix parameter when creating dirs, you only have to choice of specifying a prefix parameter.
When running the code snippet from above, you’ll get the following (or similar) output:
Note: Temp files, contrary to popular belief, do not delete themselves. You have to make sure to explicitly delete them, when creating them in unit tests or when running in production.
How to create files and directories
You’ve seen how to create temp files, and it’s the very same thing with normal files and directories. You’ll just call different methods:
Some people are confused by this: The .resolve call does not create the file, it merely returns a reference to the (child) file you are about to create.
When running the code snippet from above, you’ll get the following (or similar) output:
How to get the Posix permissions of a file
If you are running your Java program on a Unix-like system (including Linux and MacOS), you can get a file’s Posix permissions. Think: «-rw-rw-rw-» or «-rwxrwxrwx» etc.
Running this on Linux or MacOS, you would get this kind of output:
Writing & Reading Files
How to write strings to files
We haven’t talked about the core of file-handling just yet: Writing to and reading from files.
Let’s see how you can do that:
Starting with Java 11 (more specifically 11.0.2/12.0, as there was a bug in previous versions), you should be using the Files.writeString method to write string content to a file. By default, it will write a UTF-8 file, which you can, however, override by specifying a different encoding.
How to write bytes to files
Options when writing files
When calling either of the write methods, the file will automatically be created (and truncated if it already exists). Which means, we wouldn’t have had to create explicit temporary files, like we did above.
If you don’t want that behavior (i.e. fail if the file already exists) and get a corresponding exception, you’ll need to pass in another OpenOption.
Using Writers and OutputStreams
Last but not least, if you want to work directly with writers or output streams, make sure to call the corresponding Files methods and not construct the writers or streams by hand.
How to read strings from files
Reading files is very similar to writing:
On Java11+, you should be using the Files.readString method to read a string from a file. Make sure to pass in the appropriate file encoding; by default, Java will use the UTF-8 encoding to read in files.
How to read bytes from files
In case the final result should be a string, you’d then have to construct it yourself, with the appropriate encoding.
Using Readers and InputStreams
As always, you can fall back to using readers or inputstreams directly. For that, use the corresponding Files methods.
A friendly reminder: File Encodings
I’ve mentioned it a couple of times over the previous sections:
You absolutely should use an explicit encoding, whenever creating, writing to or reading from files, though it’s of big help that the new Java 11 methods default to UTF-8, and not the platform-specific encoding.
Moving, Deleting & Listing Files
There are a couple of things you need to watch out for, when moving or deleting files. Let’s see some code:
How to move files
There is a Files.move method, but it does not move a file to a designated directory (which you might expect).
test.jpg → c:\temp does not work.
test.jpg → c:\temp\test.jpg works.
So, you don’t move files to folders, but you «move» them to their full new path, including the filename and extension.
File Move Options
When moving files, you can also specify how you want to move to happen, depending on the capabilities of the underlying file system.
By default, if the target file already exists, a FileAlreadyExistsException will be thrown.
If you specify the StandardCopyOption.REPLACE_EXISTING option, the target file will be overwritten.
If you specify the StandardCopyOption.ATOMIC_MOVE option, you can move a file into a directory and be guaranteed that any process watching the directory accesses a complete file and not just a partial file.
How to delete files
Deleting files and folders is an area, where the Java Path API falls short a tiny bit. Let’s see why:
There is the Files.delete method, which allows you to delete files and directories, but directories only if they are empty.
How to delete non-empty directories
There are some 3rd-party helper libraries to work around this, but if you want to use a plain Java version to delete a non-empty directory tree, this is what you’ll want to do:
Files.walk will walk a file tree depth-first, starting with the directory you specify. The reverseOrder comparator will make sure that you delete all children, before deleting the actual directory.
Unfortunately, you’ll also need to catch the IOException, when using Files.delete inside the forEach consumer. A whole lot of code for deleting a non-empty directory, isn’t it?
Which brings us to the topic of listing files:
How to list files in the same directory
There are various ways how you can list all files in a given directory. If you only want to list files on the same levels as the directory (not recursively deeper), you can use these two methods:
It does, however, allow you to specify a glob pattern (like *.txt), which does the job for simple listings, and is maybe a bit easier to read than fumbling with real Streams and the corresponding filter methods.
Also note, that the streams returned by both methods must also be closed (e.g. with a try-with-resources statement), otherwise the JVM will keep the file handle on the directory open, which (on Windows) effectively locks it.
How to list files recursively
Note, that the stream returned by Files.walk must also be closed (e.g. with a try-with-resources statement), otherwise the JVM will keep the file handle on the directory open, which (on Windows) effectively locks it.
Absolute, Relative & Canonical Files
Let’s quickly talk about the concepts of absolute, relative & canonical paths. It’s best demonstrated with some code examples:
Relative Paths
Here, you’re constructing a new path, based on the current directory (.), even including a (..) at some point. Hence, the path is relative to your current directory, and path.isAbsolute will return false.
Absolute Paths
Normalized Paths
This normalized, absolute path, is also what you could have called the canonical path.
Relativizing Paths
Last but not least, you can also go the other way. Instead of making relative paths absolute, you can make absolute paths relative.
You’re essentially saying, given a certain base path, what is the relative path of my current (absolute) path. You’ll get the following output:
Watching Files & Directories
Some projects need to watch directories for newly created (think: uploaded) files and do something with them. You have two popular choices, when it comes to watching for changes in a directory, in Java.
Java’s WatchService
With Java 7, Java its WatchService. It is a somewhat low-level way of watching for changes in a specified directory.
Here’s some code, which you should not blindly copy & paste, but which will give you an idea of what a WatchService looks like.
Discussing a full WatchService implementation here does not really fit into the scope of this article, but note:
There’s a couple of things to watch out for (no pun intended) when using WatchService:
You might assume that you get one event, whenever e.g. a file is updated, but this can easily result in two events: One for the updated content and one for updating the last-modified timestamp, happening within a short period of time.
Complex IDEs like IntelliJ or even smaller text editors like Notepad++ don’t just save a file and its contents in one go. They copy contents to tmp files, delete them, then save the content to your actual file, etc. Again, there can be multiple updates happening to the same or even multiple files, whereas you, as the end-user, ideally would like to have just one updated event.
Hence, you’ll need to apply some workarounds. The unaccepted answer with 40+ upvotes ( Thread.sleep ) has worked somewhat reliably for me, in the past).
Last, but not least, you might want to have a look at this superb article, which talks about Java’s WatchService, Containers and issues with bind mounts.
Apache Commons-IO
There’s another library that lets you watch directories for incoming changes: Commons IO. It has the easier API from a usage perspective, but differs in two aspects from WatchService:
It uses polling, i.e. it calls the listFiles() method of the File class and compares the output with the listFiles() output of the previous iteration to see what changed.
Again, a full implementation is outside the scope of this article, but you might want to have a look at this Gist for a working code example or use the JavaDoc on FileAlterationMonitor or FileAlterationObserver as a starting point.
Here’s what the code roughly looks like, which you should not blindly copy & paste:
In-Memory File Systems
Some developers assume that working with files always means you’ll actually have to write them to your disk.
During testing, this leads to creating a lot of temp files and directories and then having to make sure to delete them again.
They let you write and read files, completely in-memory, without ever hitting your disk. Super-fast and a great fit for testing (as long as you don’t run out of memory, erm… ).
There are two Java in-memory file systems that are worth looking at.
Memory File System
One choice is Memory File System. Let’s see how you would create an in-memory filesystem with it.
Let’s break it down.
By calling newLinux() or newWindows() or newMacOs() you can control the semantics of the created file system.
You are writing to a file called somefile.txt and reading in the file contents a couple of lines later.
You’ll see why that is the case, after looking at JimFS.
JimFS
Another choice is JimFS. Let’s see how you would create an in-memory filesystem with it.
Let’s break it down.
With the Configuration.unix/windows/macOs parameter, you can control the semantics of the created file system.
You are writing to a file called somefile.txt and reading in the file contents a couple lines later.
Let’s see why that is, now.
How to make your application work with in-memory filesystems: anchors
So, while this method (and others) are very convenient, using them will imply you want to access your default FileSystem, the one your JVM is running on (WindowsFileSystem, UnixFileSystem etc.), not your in-memory FileSystem.
Hence, when wanting to make sure your code works against in-memory file systems, you must make sure to never call these helpers methods. Instead, you should always use the FileSystem or a Path as an anchor, like you are doing in the examples above.
Depending on your project (think: legacy), this is quite a challenge to pull off.
By now you should have a pretty good overview of how to work with files in Java.
How to do all basic file operations, from reading, writing, listing, moving & deleting.
How relative, absolute & canonical paths work.
How to watch directories and files.
How you can use in-memory file systems for testing.
Feedback, corrections and random input are always welcome! Simply leave a comment down below.
Thanks for reading.
Acknowledgements
Many thanks to konrad, jonhanson and DasBrain on Reddit for pointing out various small issues (needed auto-closing of file listing streams, bugs with Files.writeString, usage of the var-keyword for better readability).
There’s more where that came from
I’ll send you an update when I publish new guides. Absolutely no spam, ever. Unsubscribe anytime.
Share
Comments
I’m @MarcoBehler and I share everything I know about making awesome software through my guides, screencasts, talks and courses.
Follow me on Twitter to find out what I’m currently working on.