在Android中从文件读取/写入字符串


213

我想通过获取从EditText输入的文本来将文件保存到内部存储中。然后,我希望同一个文件以字符串形式返回输入的文本,并将其保存到另一个字符串中,以备后用。

这是代码:

package com.omm.easybalancerecharge;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText num = (EditText) findViewById(R.id.sNum);
        Button ch = (Button) findViewById(R.id.rButton);
        TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String opname = operator.getNetworkOperatorName();
        TextView status = (TextView) findViewById(R.id.setStatus);
        final EditText ID = (EditText) findViewById(R.id.IQID);
        Button save = (Button) findViewById(R.id.sButton);

        final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use

        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //Get Text From EditText "ID" And Save It To Internal Memory
            }
        });
        if (opname.contentEquals("zain SA")) {
            status.setText("Your Network Is: " + opname);
        } else {
            status.setText("No Network");
        }
        ch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //Read From The Saved File Here And Append It To String "myID"


                String hash = Uri.encode("#");
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
                        + hash));
                startActivity(intent);
            }
        });
    }

我提供了一些评论,以帮助您进一步分析我要在哪里完成操作/使用变量的观点。


2
问题是“如何从文件读取/写入文件?”
Dmitri Gudkov

您是否考虑过使用应用程序的首选项存储字符串?
sdabet 2013年

4
顺便说一句,请确保您对mainfest文件具有权限,以进行存储操作...
Dmitri Gudkov

这是我完成了一半的应用程序,需要实施许多更改。我的想法是,用户在应用程序的第一次运行中只能输入一次ID。然后,应用程序将在用户运行该应用程序时多次引用该存储的ID。权限全部添加到清单中。
Major Aly 2013年

Answers:


334

希望这对您有用。

写文件:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

读取文件:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

43
如果没有从Activity扩展该类,则“ openFileInput()”方法的用法应如下所示:context.openFileInput()
Behzad

11
注意:上面的代码运行良好,但是生成的String将不包含文件中的任何换行符。要再次添加换行符,请更改行“ stringBuilder.append(receiveString);”。到“ stringBuilder.append(receiveString).append(” \ n“);”。如果您期望其他换行符(例如Windows文本文件中将带有\ r等),则在最终字符串中,您将不得不对其进行更多调整。
treesAreEverywhere 2014年

26
此配置文件保存在实际设备中的何处?我找不到要检查的东西:(
Mahdi 2014年

4
我认为,关闭流应该final像@SharkAlley答案一样处于阻塞状态
Yurii K

4
@Kenji,文件保存在应用程序的文件目录中(即/data/data/<package_name>/files/config.txt)。应用程序的进程可以访问它,但不能访问操作系统中的所有进程。实施方式可能会有所不同,具体取决于您的设备运行的Android版本。您可以在线检查AOSP的实施。例如,对于android 8.1_r5:android.googlesource.com/platform/frameworks/base/+/…
vhamon

186

对于那些寻求读写字符串到文件的一般策略的人:

首先,获取一个文件对象

您将需要存储路径。对于内部存储,请使用:

File path = context.getFilesDir();

对于外部存储(SD卡),请使用:

File path = context.getExternalFilesDir(null);

然后创建您的文件对象:

File file = new File(path, "my-file-name.txt");

将字符串写入文件

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

或搭配Google Guava

字符串内容= Files.toString(file,StandardCharsets.UTF_8);

将文件读取为字符串

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

或者,如果您使用的是Google Guava

String contents = Files.toString(file,"UTF-8");

为了完整起见,我会提到

String contents = new Scanner(file).useDelimiter("\\A").next();

它不需要任何库,但是基准测试比其他选项要慢50%-400%(在Nexus 5上进行的各种测试)。

笔记

对于每种策略,都将要求您捕获IOException。

Android上的默认字符编码为UTF-8。

如果您使用的是外部存储,则需要将其添加到清单中:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

要么

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

写许可意味着读许可,因此您不需要两者。


好的,例如,我希望用户看到他的所有帖子,然后当他转到另一个屏幕并返回时,我是否需要再次绘制它,或者因为它已被缓存,它只是将其从缓存中拉出并显示,如果显示了只是确实将其拔出,我如何添加一个如果有条件的话说不查询我的服务器
Lion789 2014年

4
不要这样做new File(path + "/my-file-name.txt");。这违背了大多数的意识File。使用new File(path, "my-file-name.txt");代替。
JimmyB

@HannoBinder Android始终在Linux之上运行,因此分隔符保证为“ /”。在这种情况下使用新File(path,“ my-file-name.txt”)有什么好处?(如果有理由,我很乐意更新答案。)
SharkAlley 2015年

1
File在那里是有原因的。在您的情况下,您也可以跳过File并只做一次new FileInputStream(path + "/my-file-name.txt");,我不建议这样做。(例如,如果path包含尾随/该怎么办?)
JimmyB

根据您的建议进行编辑。谢谢:)
SharkAlley

37
public static void writeStringAsFile(final String fileContents, String fileName) {
    Context context = App.instance.getApplicationContext();
    try {
        FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
        out.write(fileContents);
        out.close();
    } catch (IOException e) {
        Logger.logError(TAG, e);
    }
}

public static String readFileAsString(String fileName) {
    Context context = App.instance.getApplicationContext();
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    BufferedReader in = null;

    try {
        in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
        while ((line = in.readLine()) != null) stringBuilder.append(line);

    } catch (FileNotFoundException e) {
        Logger.logError(TAG, e);
    } catch (IOException e) {
        Logger.logError(TAG, e);
    } 

    return stringBuilder.toString();
}

7
应用程式!它应该是什么!
2014年

@alap是@Eugene用于静态检索应用程序上下文的东西。他需要它context.getFilesDir()。您可以new File(context.getFilesDir(), fileName)File对象或String传递给函数的代替的出现fileName
lorenzo-s 2015年

7

只需对从文件方法读取字符串进行一些修改即可获得更高的性能

private String readFromFile(Context context, String fileName) {
    if (context == null) {
        return null;
    }

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput(fileName);

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);               

            int size = inputStream.available();
            char[] buffer = new char[size];

            inputStreamReader.read(buffer);

            inputStream.close();
            ret = new String(buffer);
        }
    }catch (Exception e) {
        e.printStackTrace();
    }

    return ret;
}

6

检查以下代码。

从文件系统中的文件读取。

FileInputStream fis = null;
    try {

        fis = context.openFileInput(fileName);
        InputStreamReader isr = new InputStreamReader(fis);
        // READ STRING OF UNKNOWN LENGTH
        StringBuilder sb = new StringBuilder();
        char[] inputBuffer = new char[2048];
        int l;
        // FILL BUFFER WITH DATA
        while ((l = isr.read(inputBuffer)) != -1) {
            sb.append(inputBuffer, 0, l);
        }
        // CONVERT BYTES TO STRING
        String readString = sb.toString();
        fis.close();

    catch (Exception e) {

    } finally {
        if (fis != null) {
            fis = null;
        }
    }

下面的代码是将文件写入内部文件系统。

FileOutputStream fos = null;
    try {

        fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(stringdatatobestoredinfile.getBytes());
        fos.flush();
        fos.close();

    } catch (Exception e) {

    } finally {
        if (fos != null) {
            fos = null;
        }
    }

我认为这会对您有所帮助。


3

我有点初学者,现在很难使它工作。

下面是我最后的课程。它有效,但我想知道我的解决方案有多不完善。无论如何,我希望某些经验丰富的人可能愿意看一下我的IO课并给我一些提示。干杯!

public class HighScore {
    File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
    File file = new File(data, "highscore.txt");
    private int highScore = 0;

    public int readHighScore() {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            try {
                highScore = Integer.parseInt(br.readLine());
                br.close();
            } catch (NumberFormatException | IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            try {
                file.createNewFile();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            e.printStackTrace();
        }
        return highScore;
    }

    public void writeHighScore(int highestScore) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(String.valueOf(highestScore));
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果没有文件,则无需创建新文件。
毫升

1

我们需要的第一件事是AndroidManifest.xml中的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

因此,在asyncTask Kotlin类中,我们将处理文件的创建

    import android.os.AsyncTask
    import android.os.Environment
    import android.util.Log
    import java.io.*
    class WriteFile: AsyncTask<String, Int, String>() {
        private val mFolder = "/MainFolder"
        lateinit var folder: File
        internal var writeThis = "string to cacheApp.txt"
        internal var cacheApptxt = "cacheApp.txt"
        override fun doInBackground(vararg writethis: String): String? {
            val received = writethis[0]
            if(received.isNotEmpty()){
                writeThis = received
            }
            folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
            if(!folder.exists()){
                folder.mkdir()
                val readME = File(folder, cacheApptxt)
                val file = File(readME.path)
                val out: BufferedWriter
                try {
                    out = BufferedWriter(FileWriter(file, true), 1024)
                    out.write(writeThis)
                    out.newLine()
                    out.close()
                    Log.d("Output_Success", folder.path)
                } catch (e: Exception) {
                    Log.d("Output_Exception", "$e")
                }
            }
            return folder.path

    }

        override fun onPostExecute(result: String) {
            super.onPostExecute(result)

            if(result.isNotEmpty()){
                //implement an interface or do something
                Log.d("onPostExecuteSuccess", result)
            }else{
                Log.d("onPostExecuteFailure", result)
            }
        }

    }

当然,如果您使用的是高于Api 23的Android,则必须处理该请求以允许写入设备内存。像这样

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class ReadandWrite {
        private val mREAD = 9
        private val mWRITE = 10
        private var readAndWrite: Boolean = false
        fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
            if (Build.VERSION.SDK_INT < 23) {
                readAndWrite = true
            } else {
                val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
                val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                if (mRead != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
                } else {
                    readAndWrite = true
                }

                if (mWrite != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
                } else {
                    readAndWrite = true
                }
            }
            return readAndWrite
        }
    }

然后在一个活动中执行调用。

  var pathToFileCreated = ""
    val anRW = ReadandWrite().readAndwriteStorage(this,this)
    if(anRW){
        pathToFileCreated =  WriteFile().execute("onTaskComplete").get()
        Log.d("pathToFileCreated",pathToFileCreated)
    }

这些内部存储权限无效。
Lerk

0

科特林

class FileReadWriteService {

    private var context:Context? = ContextHolder.instance.appContext

    fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
        val file = File(context?.filesDir, "files")
        try {
            if (!file.exists()) {
                file.mkdir()
            }
            val fileToWrite = File(file, fileKey)
            val writer = FileWriter(fileToWrite)
            writer.append(sBody)
            writer.flush()
            writer.close()
        } catch (e: Exception) {
            Logger.e(classTag, e)
        }
    }

    fun readFileOnInternalStorage(fileKey: String): String {
        val file = File(context?.filesDir, "files")
        var ret = ""
        try {
            if (!file.exists()) {
                return ret
            }
            val fileToRead = File(file, fileKey)
            val reader = FileReader(fileToRead)
            ret = reader.readText()
            reader.close()
        } catch (e: Exception) {
            Logger.e(classTag, e)
        }
        return ret
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.