1. 程式人生 > >android 從java到C層檔案讀取流程

android 從java到C層檔案讀取流程

Java中常用的檔案讀寫的兩個類:

1.FileInputStream/FileOutputStream(FileReader/FileWriter)

2.RandomFileAccess

FileInputSteamFileOutputStream繼承於InputStreamOutputStreamFileReaderFileWriter繼承於ReaderWriter,它們的底層實現原理其實是樣的,區別在於一個前者用於位元組型資料流讀寫,後者用於unicode文字流讀寫

RandomFileAccess是一個獨立的檔案讀寫類,它與InputStreamOutputStream不同之處在於它更傾向與隨機檔案讀寫,類似

C語言fopenfreadfseekfwritefflushfclose的封裝。

eg.FileOutputStream

File file2 = new File("FileOut.txt");

if(file2 == null)

{

            dbgOutput("ERR","File 2 Can't make");

            return;

}

FileOutputStream fos = new FileOutputStream(file2); //此處才會建立檔案出來

if(fos == null)

{                                 

        dbgOutput("ERR","File 2 Output stream can't make");

        return;

}

byte [] words = {'a','b','c','d','e'};

fos.write(words);

fos.flush();

fos.close();

eg.RandomAccessFile

RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw"); 

        for (int i = 0; i < 10; i++) { 

            //寫入基本型別

double資料 

            rf.writeDouble(i * 1.414); 

        } 

        rf.close(); 

        rf = new RandomAccessFile("rtest.dat", "rw"); 

        //直接將檔案指標移到第5double資料後面 

        rf.seek(5 * 8); 

        //覆蓋第6double資料 

        rf.writeDouble(47.0001); 

        rf.close(); 

        rf = new RandomAccessFile("rtest.dat", "r"); 

        for (int i = 0; i < 10; i++) { 

            System.out.println("Value " + i + ": " + rf.readDouble()); 

        } 

        rf.close(); 

Android Java 檔案讀寫IO類的具體實現的程式碼在libcore中實現,原理也是通過JNI的方式實現的,對於

FileInputStreamFileOutStream類,繼承於InputStreamOutputStream類,但InputStreamOutputStream只聲明瞭抽象的readwrite介面,如:

@ \libcore\luni\src\main\java\java\io\InputStream.java

@ \libcore\luni\src\main\java\java\io\OutputStream.java

public abstract int read() throws IOException;

public abstract void write(int oneByte) throws IOException;

具體的實現還是在FileInputStreamFileOutputStream中重寫的,其中實現的程式碼如下:

@ \libcore\luni\src\main\java\java\io\FileInputStream.java

@ \libcore\luni\src\main\java\java\io\FileOutputStream.java

    @Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {

        return IoBridge.read(fd, buffer, byteOffset, byteCount);

    }

    public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException {

        IoBridge.write(fd, buffer, byteOffset, byteCount);

    }

其中呼叫了IoBridge類實現,readwrite方法都是靜態方法,實現的程式碼如下:

@ \android\libcore\luni\src\main\java\libcore\io\IoBridge.java

read方法

   /**

     * java.io thinks that a read at EOF is an error and should return -1, contrary to traditional

     * Unix practice where you'd read until you got 0 bytes (and any future read would return -1).

     */

    public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {

        Arrays.checkOffsetAndCount(bytes.length, byteOffset, byteCount);

        if (byteCount == 0) {

            return 0;

        }

        try {

            int readCount = Libcore.os.read(fd, bytes, byteOffset, byteCount);

            if (readCount == 0) {

                return -1;

            }

            return readCount;

        } catch (ErrnoException errnoException) {

            if (errnoException.errno == EAGAIN) {

                // We return 0 rather than throw if we try to read from an empty non-blocking pipe.

                return 0;

            }

            throw errnoException.rethrowAsIOException();

        }

    }

@ \android\libcore\luni\src\main\java\libcore\io\IoBridge.java

write方法:

/**

     * java.io always writes every byte it's asked to, or fails with an error. (That is, unlike

     * Unix it never just writes as many bytes as happens to be convenient.)

     */

    public static void write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {

        Arrays.checkOffsetAndCount(bytes.length, byteOffset, byteCount);

        if (byteCount == 0) {

            return;

        }

        try {

            while (byteCount > 0) {

                int bytesWritten = Libcore.os.write(fd, bytes, byteOffset, byteCount);

                byteCount -= bytesWritten;

                byteOffset += bytesWritten;

            }

        } catch (ErrnoException errnoException) {

            throw errnoException.rethrowAsIOException();

        }

    }

LibCore類只有Os這一個物件:

\libcore\luni\src\main\java\libcore\io\LibCore.java

package libcore.io;

public final class Libcore {

    private Libcore() { }

    public static Os os = new BlockGuardOs(new Posix());

}

Os物件是一系列系統呼叫的抽象介面,從LibCore.java中可以看出它是通過Posix這個類實現的,這個類中讀寫的實現如下:

@\libcore\luni\src\main\java\libcore\io\Posix.java

    public int read(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException {

        if (buffer.isDirect()) {

            return readBytes(fd, buffer, buffer.position(), buffer.remaining());

        } else {

            return readBytes(fd, NioUtils.unsafeArray(buffer), NioUtils.unsafeArrayOffset(buffer) + buffer.position(), buffer.remaining());

        }

    }

    public int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException {

        // This indirection isn't strictly necessary, but ensures that our public interface is type safe.

        return readBytes(fd, bytes, byteOffset, byteCount);

    }

    private native int readBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException;

  public int write(FileDescriptor fd, ByteBuffer buffer) throws ErrnoException {

        if (buffer.isDirect()) {

            return writeBytes(fd, buffer, buffer.position(), buffer.remaining());

        } else {

            return writeBytes(fd, NioUtils.unsafeArray(buffer), NioUtils.unsafeArrayOffset(buffer) + buffer.position(), buffer.remaining());

        }

    }

    public int write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws ErrnoException {

        // This indirection isn't strictly necessary, but ensures that our public interface is type safe.

        return writeBytes(fd, bytes, byteOffset, byteCount);

    }

    private native int writeBytes(FileDescriptor fd, Object buffer, int offset, int byteCount) throws ErrnoException;

最終是通過native呼叫來實現的,

@\libcore\luni\src\main\native\libcore_io_Posix.cpp

static jint Posix_writeBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount) {

    ScopedBytesRO bytes(env, javaBytes);

    if (bytes.get() == NULL) {

        return -1;

    }

    int fd = jniGetFDFromFileDescriptor(env, javaFd);

    return throwIfMinusOne(env, "write", TEMP_FAILURE_RETRY(write(fd, bytes.get() + byteOffset, byteCount)));

}

static jint Posix_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) {

    ScopedBytesRW bytes(env, javaBytes);

    if (bytes.get() == NULL) {

        return -1;

    }

    int fd = jniGetFDFromFileDescriptor(env, javaFd);

    return throwIfMinusOne(env, "read", TEMP_FAILURE_RETRY(read(fd, bytes.get() + byteOffset, byteCount)));

}

對於RandomAccessFile的呼叫過程:

@\libcore\luni\src\main\java\java\io\RandomAccessFile.java

    public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {

        return IoBridge.read(fd, buffer, byteOffset, byteCount);

    }

    public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException {

        IoBridge.write(fd, buffer, byteOffset, byteCount);

        // if we are in "rws" mode, attempt to sync file+metadata

        if (syncMetadata) {

            fd.sync();

        }

    }

雖然RandomAccessFilejava中是與FileInputStreamFileOutputStream設計得完全不同的類,但其底層實現還是一樣的。