- Java Read Files
- Example
- Get File Information
- Example
- Reading Class Files
- Bare Bones 1:1 Representation of Java Class Files
- Object-Oriented Representation of Java Class Files
- Representing entire Java Projects
- 3-Address Code Representation
- How to read .class file? [duplicate]
- 3 Answers 3
- How to Read Files in Java
- Reading Text Files in Java with BufferedReader
- Reading UTF-8 Encoded File in Java with BufferedReader
- Using Java Files Class to Read a File
- Reading Small Files in Java with Files Class
- Reading Large Files in Java with Files Class
- Reading Files with Files.lines()
- Reading Text Files in Java with Scanner
- Reading an Entire File
- Conclusion
Java Read Files
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter:
Example
import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; // Import the Scanner class to read text files public class ReadFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) < String data = myReader.nextLine(); System.out.println(data); >myReader.close(); > catch (FileNotFoundException e) < System.out.println("An error occurred."); e.printStackTrace(); >> >
Get File Information
To get more information about a file, use any of the File methods:
Example
import java.io.File; // Import the File class public class GetFileInfo <
public static void main(String[] args) < File myObj = new File("filename.txt"); if (myObj.exists()) < System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); >else < System.out.println("The file does not exist."); >> >
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc. Which one to use depends on the Java version you’re working with and whether you need to read bytes or characters, and the size of the file/lines etc.
Tip: To delete a file, read our Java Delete Files chapter.
Reading Class Files
OPAL provides multiple different representations for Java class files to support different use cases. Next, we will discuss how to directly read Java class files and how to create the different representations.
The following examples expect that you have checked out OPAL, and that you started sbt in OPAL’s main folder. After that, you have changed to the project project OPAL-DeveloperTools and started the console . Alternatively to checking out OPAL and building OPAL on your own, you can use our preconfigured Docker Container.
A growing number of small code snippets that demonstrate various aspects of the API can be found here.
Bare Bones 1:1 Representation of Java Class Files
A bit by bit representation is provided by the bytecode disassembler sub project. In this representation, the constant pool is kept and all other elements (e.g., names of classes, methods and fields, but also constant values etc.) use int based references to the constant pool to refer to the respective values. A single class file can trivially be loaded using:
import java.io. import org.opalj.io.process import org.opalj.da.ClassFile val classFileName = "OPAL/ai/target/scala-2.13/classes/org/opalj/ai/AI.class" val cfs : List[ClassFile] = process(new DataInputStream(new FileInputStream(classFileName))) < in =>org.opalj.da.ClassFileReader.ClassFile(in) >
When you use this representation, the returned list always contains a single class file object – which you can get by calling head on the returned list.
Using this representation is very, very fast and makes it, e.g., easily possible to perform some simple method based slicing or to create an HTML representation (by calling toXHTML ). The loaded class/transformed class can be written to a class file using org.opalj.bc.Assembler()
Object-Oriented Representation of Java Class Files
In most cases, an explicit representation of the constant pool actually complicates the implementation of static analyses. To avoid that you have to deal with the constant pool, OPAL provides a standard object oriented representation that suits many needs. This representation is still stack based and, therefore, the operand stack is still present. It, nevertheless, often strikes a nice balance between performance, memory usage and convenience and, therefore, many analyses that are part of OPAL use this representation. In general, a list of class files is returned to support class file transformations while the class file is loaded. For example – if configured – invokedynamic instructions, which are, e.g., created by Java compilers when closures are used in Java code, will automatically be transformed to standard (pre Java 7) classes and method calls to faciliate subsequent analyses. In this case, a class is generated that will capture the closure’s call state and the invokedynamic instruction will be replaced by a call to the generated class’ factory method; this class serves a similar purpose as the call-site object that would be created by the JVM at runtime.
import java.io. import org.opalj.io.process import org.opalj.br.ClassFile // "br" instead of "da" val classFileName = "OPAL/ai/target/scala-2.13/classes/org/opalj/ai/AI.class" val cfs : List[ClassFile] = process(new DataInputStream(new FileInputStream(classFileName))) < in =>org.opalj.br.reader.Java8Framework.ClassFile(in) >
Representing entire Java Projects
Instead of reading the class files on your own, it is also possible to directly create a Project which also directly makes the class hierarchy available and offers many methods related to resolving method calls and the like. A Project is usually at the core of implementing static analyses on top of OPAL. To read more about it go here.
3-Address Code Representation
On top/based on the object oriented representation OPAL provides a third representation based on 3-address code/quadruples in single static assignment (SSA) form. This representation is directly made available by a Project on-demand. To read more about it go here.
How to read .class file? [duplicate]
I need to read the contents of .class file of java in my java program or is there any method available to read the same.Actually I want to retrieve the local variable table ,line number table,etc from .class file of java but I’m not getting any method to read the same?
3 Answers 3
I want to retrieve the local variable table ,line number table,etc
To read those you will need ASM, BCEL or a similar bytecode library. Java’s reflection API does not tell them to you.
You need a Java decompiler or something like that
Basically my project is to generate the test cases using white box testing.Normally our NetBeans or eclipse have their own editors,where they can compile their code and also generate the test cases.But waht we have to do is read the .java file stored in the disk anywhere and generate the test cases.And for that we are actually searching for how to get the symbols ,their data type ,its value,etc..And I was thinking to read a .class file as it contains local variable table,line number table,etc. And so we are not using any tool
You can get these info using BCEL
The Byte Code Engineering Library is intended to give users a convenient possibility to analyze, create, and manipulate (binary) Java class files (those ending with .class). Classes are represented by objects which contain all the symbolic information of the given class: methods, fields and byte code instructions, in particular.
Or You can also Use Reflection API to get info from class file
Reflection does not get info from the class file but from the class object (after the class loader has done its job)
How to Read Files in Java
Java provides several methods to read files. Each of these methods is appropriate for reading different types of files in different situations. Some are better for reading longer files, others are better for reading shorter ones, etc.
In this tutorial, we will be using the following Java classes to read files
Throughout the tutorial, we are using a file stored in the src directory where the path to the file is src/file.txt .
Store several lines of text in this file before proceeding.
Note: You have to properly handle the errors when using these implementations to stick to the best coding practices.
Reading Text Files in Java with BufferedReader
The BufferedReader class reads a character-input stream. It buffers characters in a buffer with a default size of 8 KB to make the reading process more efficient. If you want to read a file line by line, using BufferedReader is a good choice.
BufferedReader is efficient in reading large files.
import java.io.*; public class FileReaderWithBufferedReader < public static void main(String[] args) throws IOExceptionbufferedReader.close(); > >
The readline() method returns null when the end of the file is reached.
Reading UTF-8 Encoded File in Java with BufferedReader
We can use the BufferedReader class to read a UTF-8 encoded file.
This time, we pass an InputStreamReader object when creating a BufferedReader instance.
import java.io.*; public class EncodedFileReaderWithBufferedReader < public static void main(String[] args) throws IOException < String file = "src/fileUtf8.txt"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String curLine; while ((curLine = bufferedReader.readLine()) != null)< //process the line as you require System.out.println(curLine); >> >
Using Java Files Class to Read a File
Java Files class, introduced in Java 7 in Java NIO, consists fully of static methods that operate on files.
Using Files class, you can read the full content of a file into an array. This makes it a good choice for reading smaller files.
Let’s see how we can use Files class in both these scenarios.
Reading Small Files in Java with Files Class
The readAllLines() method of the Files class allows reading the whole content of the file and stores each line in an array as strings.
You can use the Path class to get the path to the file since the Files class accepts the Path object of the file.
import java.io.IOException; import java.nio.file.*; import java.util.*; public class SmallFileReaderWithFiles < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); Listlines = Files.readAllLines(path); > >
You can use readAllBytes() to retrieve the data stored in the file to a byte array instead of a string array.
byte[] bytes = Files.readAllBytes(path);
Reading Large Files in Java with Files Class
If you want to read a large file with the Files class, you can use the newBufferedReader() method to obtain an instance of BufferedReader class and read the file line by line using a BufferedReader .
import java.io.*; import java.nio.file.*; public class LargeFileReaderWithFiles < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); BufferedReader bufferedReader = Files.newBufferedReader(path); String curLine; while ((curLine = bufferedReader.readLine()) != null)< System.out.println(curLine); >bufferedReader.close(); > >
Reading Files with Files.lines()
Java 8 introduced a new method to the Files class to read the whole file into a Stream of strings.
import java.io.IOException; import java.nio.file.*; import java.util.stream.Stream; public class FileReaderWithFilesLines < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); Streamlines = Files.lines(path); lines.forEach(s -> System.out.println(s)); lines.close(); > >
Reading Text Files in Java with Scanner
The Scanner class breaks the content of a file into parts using a given delimiter and reads it part by part. This approach is best suited for reading content that is separated by a delimiter.
For example, the Scanner class is ideal for reading a list of integers separated by white spaces or a list of strings separated by commas.
The default delimiter of the Scanner class is whitespace. But you can set the delimiter to another character or a regular expression. It also has various next methods, such as next() , nextInt() , nextLine() , and nextByte() , to convert content into different types.
import java.io.IOException; import java.util.Scanner; import java.io.File; public class FileReaderWithScanner < public static void main(String[] args) throws IOException< String file = "src/file.txt"; Scanner scanner = new Scanner(new File(file)); scanner.useDelimiter(" "); while(scanner.hasNext())< String next = scanner.next(); System.out.println(next); >scanner.close(); > >
In the above example, we set the delimiter to whitespace and use the next() method to read the next part of the content separated by whitespace.
Reading an Entire File
You can use the Scanner class to read the entire file at once without running a loop. You have to pass “\\Z” as the delimiter for this.
scanner.useDelimiter("\\Z"); System.out.println(scanner.next()); scanner.close();
Conclusion
As you saw in this tutorial, Java offers many methods that you can choose from according to the nature of the task at your hand to read text files. You can use BufferedReader to read large files line by line.
If you want to read a file that has its content separated by a delimiter, use the Scanner class.
Also you can use Java NIO Files class to read both small and large files.