同时在Android中从NDK写入和读取文件 [英] Simultaneously write and read a file from NDK in android

查看:702
本文介绍了同时在Android中从NDK写入和读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用android-ndk写入文件.因此,使用本机C代码进行文件写操作.

I am writing into a file using android-ndk . So writing in file is taking place using native c code.

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

It contains some kind of readings that i am putting in using ndk. On click of a button the writing into a file start. And simultaneously i want to read contents of file and use them into another thread for showing up the values as writing operation might continue for 15 sec and user will have to wait for that much time to see the result so i want to show result one by one as soon as i get it into that file.

这可行吗,如果可以,请告诉我该怎么做?

Is it feasible ,if yes can show me the way how to go about that?

好吧,我从它开始,然后就开始了它的工作方式,

Well i started with it and right nw its how i am doing it ,,

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打开

nativeFunction opens

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

此功能可在文件中持续写入内容约2分钟, 但是我需要不断获取由本机函数输入的值,因此我启动了第二个线程,但是当我检查file.length()时,它始终为0.

This function keeps on writing things in file for around 2 minutes, but i need to continuously get the values entered bye native function so i started 2nd thread but when i check file.length() its always 0.

,并且当完成本机功能写入时,就会出现实际文件大小.那么如何解决这个问题呢?

and when nativefunction write is complete then actual file size comes. So how to get around this problem?

推荐答案

使用pthreads应该可以实现.因此,您需要生成2个线程,一个线程进行写操作,另一个线程进行读操作.如果您是从同一文件执行此操作,则可能会遇到争用情况,因此请小心.

This should be possible using pthreads. So you need to spawn 2 threads, one doing the writing and other doing the reading. If you are doing it from the same file, you may run into race conditions, so be careful.

有关pthread的更多信息,请谷歌.它是Linux世界中常用的.

More more info on pthreads, kindly google. It's commonly used by the Linux world.

这篇关于同时在Android中从NDK写入和读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆