From 2c0a1c726dd0520607ef6478b9cd7998165fdd56 Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Thu, 17 Oct 2013 14:46:00 -0500 Subject: [PATCH] Add write support for RandomAccessFile Signed-off-by: Johannes Schindelin --- classpath/java-io.cpp | 46 +++++++++++++++++++++++++ classpath/java/io/RandomAccessFile.java | 8 +++++ 2 files changed, 54 insertions(+) diff --git a/classpath/java-io.cpp b/classpath/java-io.cpp index 462bed8ada..d461bb7b0c 100644 --- a/classpath/java-io.cpp +++ b/classpath/java-io.cpp @@ -898,6 +898,52 @@ Java_java_io_RandomAccessFile_readBytes(JNIEnv* e, jclass, jlong peer, return (jint)bytesRead; } +extern "C" JNIEXPORT jint JNICALL +Java_java_io_RandomAccessFile_writeBytes(JNIEnv* e, jclass, jlong peer, + jlong position, jbyteArray buffer, + int offset, int length) +{ +#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + int fd = (int)peer; + if(::lseek(fd, position, SEEK_SET) == -1) { + throwNewErrno(e, "java/io/IOException"); + return -1; + } + + uint8_t* dst = reinterpret_cast + (e->GetPrimitiveArrayCritical(buffer, 0)); + + int64_t bytesWritten = ::write(fd, dst + offset, length); + e->ReleasePrimitiveArrayCritical(buffer, dst, 0); + + if(bytesWritten == -1) { + throwNewErrno(e, "java/io/IOException"); + return -1; + } +#else + HANDLE hFile = (HANDLE)peer; + LARGE_INTEGER lPos; + lPos.QuadPart = position; + if(!SetFilePointerEx(hFile, lPos, nullptr, FILE_BEGIN)) { + throwNewErrno(e, "java/io/IOException"); + return -1; + } + + uint8_t* dst = reinterpret_cast + (e->GetPrimitiveArrayCritical(buffer, 0)); + + DWORD bytesWritten = 0; + if(!WriteFile(hFile, dst + offset, length, &bytesWritten, nullptr)) { + e->ReleasePrimitiveArrayCritical(buffer, dst, 0); + throwNewErrno(e, "java/io/IOException"); + return -1; + } + e->ReleasePrimitiveArrayCritical(buffer, dst, 0); +#endif + + return (jint)bytesWritten; +} + extern "C" JNIEXPORT void JNICALL Java_java_io_RandomAccessFile_close(JNIEnv* /* e*/, jclass, jlong peer) { diff --git a/classpath/java/io/RandomAccessFile.java b/classpath/java/io/RandomAccessFile.java index c2398b414b..efb1de6ab2 100644 --- a/classpath/java/io/RandomAccessFile.java +++ b/classpath/java/io/RandomAccessFile.java @@ -131,6 +131,14 @@ public class RandomAccessFile { private static native int readBytes(long peer, long position, byte[] buffer, int offset, int length); + public void write(int b) throws IOException { + int count = writeBytes(peer, position, new byte[] { (byte)b }, 0, 1); + if (count > 0) position += count; + } + + private static native int writeBytes(long peer, long position, byte[] buffer, + int offset, int length); + public void close() throws IOException { if (peer != 0) { close(peer);