如何从Android中的文件读取/写入字符串

Maj*_*Aly 184 java string file-io android

我想通过获取从EditText输入的文本将文件保存到内部存储.然后我希望同一个文件以String形式返回输入的文本并将其保存到另一个稍后要使用的String中.

这是代码:

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);
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

我已经包含了一些注释,可以帮助您进一步分析我的想法,即我希望在哪里进行操作/使用变量.

R9J*_*R9J 313

希望这可能对你有用.

写文件:

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());
    } 
}
Run Code Online (Sandbox Code Playgroud)

阅读文件:

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(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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果类没有从Activity扩展,那么"openFileInput()"方法的用法应该是这样的:context.openFileInput() (42认同)
  • 这个配置文件在真实设备中保存的位置?我找不到它来检查:( (23认同)
  • 注意:上面的代码运行良好,但生成的String不包含文件中的任何换行符.要再次添加换行符,请更改行"stringBuilder.append(receiveString);" to"stringBuilder.append(receiveString).append("\n");".如果你期望其他换行符(例如Windows文本文件将有\ r等等),在你的最后一个字符串中,你将不得不更多地调整它. (9认同)
  • 我认为,关闭流应该在@ScherkAlley回答中的'final`块中 (4认同)
  • @saganaut - 我在谈论finally块:`finally {inputStream.close();}`.对于终结者 - 这是真的,你不能依赖它们来关闭资源 (2认同)
  • @Kenji,文件保存在应用程序的文件目录中(即/data/data/<package_name>/files/config.txt)。应用程序的进程可以访问它,但不能访问操作系统中的所有进程。实现可能会有所不同,具体取决于您的设备运行的Android版本。您可以在线检查AOSP的实施。例如,对于android 8.1_r5:https://android.googlesource.com/platform/frameworks/base/+/android-cts-8.1_r5/core/java/android/app/ContextImpl.java#531 (2认同)

Sha*_*ley 171

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

首先,获取一个文件对象

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

File path = context.getFilesDir();
Run Code Online (Sandbox Code Playgroud)

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

File path = context.getExternalFilesDir(null);
Run Code Online (Sandbox Code Playgroud)

然后创建您的文件对象:

File file = new File(path, "my-file-name.txt");
Run Code Online (Sandbox Code Playgroud)

将字符串写入文件

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

或者使用Google Guava

String contents = 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);   
Run Code Online (Sandbox Code Playgroud)

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

String contents = Files.toString(file,"UTF-8");
Run Code Online (Sandbox Code Playgroud)

为了完整,我会提到

String contents = new Scanner(file).useDelimiter("\\A").next();
Run Code Online (Sandbox Code Playgroud)

它不需要库,但基准测试比其他选项慢50%-400%(在我的Nexus 5的各种测试中).

笔记

对于这些策略中的每一个,都会要求您捕获IOException.

Android上的默认字符编码是UTF-8.

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

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

要么

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

写入权限意味着读取权限,因此您不需要两者.

  • 不要像`new File(path +"/ my-file-name.txt");`那样做.这违背了"文件"的大部分意义.使用`new File(path,"my-file-name.txt");`代替. (4认同)
  • `File` 存在是有原因的。在你的情况下,你也可以跳过`File`,只做`new FileInputStream(path + "/my-file-name.txt");`,我不推荐这样做。(例如,如果 `path` 包含一个尾随的 `/` 怎么办?) (2认同)

Eug*_*ene 33

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();
}
Run Code Online (Sandbox Code Playgroud)

  • App !? 应该是什么样的! (6认同)

Dar*_*han 10

Kotlin使用内置扩展功能的方式File

yourFile.writeText(textFromEditText)
读: yourFile.readText()


Tai*_*Anh 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;
}
Run Code Online (Sandbox Code Playgroud)


Raj*_*Raj 5

检查以下代码.

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

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想这会对你有所帮助.


小智 5

我是个初学者,今天很难让它发挥作用。

下面是我最终的课程。它有效,但我想知道我的解决方案有多不完美。不管怎样,我希望你们中一些更有经验的人愿意看看我的 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)