How do the JVM and Java implement read and write to files?

In Java, you can read and write files. But the JVM can run on many systems, which can have different ways of storing files and related data. How to write JVM code that works on every system?

At what level do you use your own methods? Does the JVM have a specific set of file functions that must be implemented for each system and which can then be called in any language? Or should every language that runs on the JVM (like Java or Scala) do this on its own?

+6
source share
3 answers

Typically, you should write the JVM in a high-level language such as C ++, and then use these languages ​​for libraries to interact with the file system. You can then compile the JVM on different platforms, operating systems, and architectures and take responsibility for deciding how to input / output files to a high-level compiler.

Alternatively, for certain operations, the JVM may have different file / window I / O implementations based on the operating system it runs on. Then there will be many different implementations, and when creating the JVM in the system, the compiler can determine which one to use based on the config script or #ifdef s, etc.

Hope this helps!

+6
source

Most I / O functions are pretty standard, and there are POSIX calls that work on many operating systems. Where there are differences, the corresponding code may or may not be used with the C preprocessor with #ifndef and #ifndef

+1
source

Reading and writing to a file is performed in the java.io.FileInputStream / FileOutputStream classes by calling custom methods, for example

 private native int readBytes(byte b[], int off, int len) throws IOException; private native void writeBytes(byte b[], int off, int len, boolean append) throws IOException; 

These classes are the same for all platforms, but only the implementation of native methods is different in my Oracle HotSpot it jre/bin/java.dll

+1
source

Source: https://habr.com/ru/post/947062/


All Articles