implement File.list and File.mkdirs

This commit is contained in:
Zsombor 2008-07-13 18:14:37 -06:00 committed by Joel Dice
parent a016eeaba0
commit 2e0ca31148
2 changed files with 97 additions and 0 deletions

View File

@ -14,6 +14,7 @@
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include "jni.h"
#include "jni-util.h"
@ -202,6 +203,42 @@ Java_java_io_File_exists(JNIEnv* e, jclass, jstring path)
}
}
extern "C" JNIEXPORT jlong JNICALL
Java_java_io_File_openDir(JNIEnv* e, jclass, jstring path)
{
const char* chars = e->GetStringUTFChars(path, 0);
if (chars) {
jlong handle = reinterpret_cast<jlong>(opendir(chars));
e->ReleaseStringUTFChars(path, chars);
return handle;
} else {
return 0;
}
}
extern "C" JNIEXPORT jstring JNICALL
Java_java_io_File_readDir(JNIEnv* e, jclass, jlong handle)
{
struct dirent * directoryEntry;
if (handle!=0) {
directoryEntry = readdir(reinterpret_cast<DIR*>(handle));
if (directoryEntry == NULL) {
return NULL;
}
return e->NewStringUTF(directoryEntry->d_name);
}
return NULL;
}
extern "C" JNIEXPORT void JNICALL
Java_java_io_File_closeDir(JNIEnv* , jclass, jlong handle)
{
if (handle!=0) {
closedir(reinterpret_cast<DIR*>(handle));
}
}
extern "C" JNIEXPORT jint JNICALL
Java_java_io_FileInputStream_open(JNIEnv* e, jclass, jstring path)
{

View File

@ -126,4 +126,64 @@ public class File {
return false;
}
}
public boolean mkdirs() {
File parent = getParentFile();
if (parent != null) {
if (!parent.exists()) {
if (!parent.mkdirs()) {
return false;
}
}
}
return mkdir();
}
public String[] list() {
return list(null);
}
public String[] list(FilenameFilter filter) {
long handle = 0;
try {
handle = openDir(path);
Pair list = null;
int count = 0;
for (String s = readDir(handle); s != null; s = readDir(handle)) {
if (filter == null || filter.accept(this, s)) {
list = new Pair(s, list);
++ count;
}
}
String[] result = new String[count];
for (int i = count; i >= 0; --i) {
result[i] = list.value;
list = list.next;
}
return result;
} finally {
if (handle != 0) {
closeDir(handle);
}
}
}
private static native long openDir(String path);
private static native String readDir(long handle);
private static native long closeDir(long handle);
private static class Pair {
public final String value;
public final Pair next;
public Pair(String value, Pair next) {
this.value = value;
this.next = next;
}
}
}