同时在android中从NDK写入和读取文件

时间:2012-10-12 09:36:47

标签: android android-ndk android-file

我正在使用android-ndk写入文件。因此,使用本机c代码进行文件写入。

它包含一些我正在使用ndk的读数。 单击按钮,开始写入文件。同时我想读取文件的内容并将它们用于另一个线程以显示值,因为写入操作可能会持续15秒,用户将不得不等待那么多时间才能看到结果,所以我想显示结果一个一旦我把它放进那个文件就一个。

是否可行,如果是的话可以告诉我如何去做?

我开始使用它并且正确地知道我在做什么,

Thread thr1 = new Thread(r1);
Thread thr2 = new Thread(r2);
thr1.start();
thr2.start();



r1 = new Runnable() {
          public void run() {
            File sdcard= Environment.getExternalStorageDirectory();
            nativeFunction(sdcard +"/readings.txt");
            //takingReading=false;
            readingFile = new File(sdcard +"/readings.txt");

            Log.i("length of file", ""+readingFile.length());
          }
        };




r2 = new Runnable() {
          public void run() {
            try {

                  Thread.sleep(3000);
                  File sdcard= Environment.getExternalStorageDirectory();

                readingFile = new File(sdcard +"/readings.txt");

                Log.i("length of file", ""+readingFile.length());


            } catch (InterruptedException iex) {}
          }
        };

nativeFunction打开

file= fopen(location,"w+");

此功能继续将文件写入文件大约2分钟, 但我需要不断获取由本机函数输入的值,所以我开始第二个线程但是当我检查file.length()时它总是为0。

当nativefunction write完成后,就会出现实际的文件大小。那么如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这应该可以使用pthreads。所以你需要产生2个线程,一个做写作,另一个做读取。如果你是从同一个文件中进行的,那么你可能会遇到竞争条件,所以要小心。

有关pthreads的更多信息,请点击谷歌。它通常被Linux世界使用。