android 用 sdcard 文件中的另一个字符串替换字符串

android replace string by another string in file on sdcard

我在 sdcard 上创建了 Test.txt 并在上面写了字符串 "test example"。
之后,我将字符串 "test" 替换为 "etc" in Test.txt.
这是我的代码:

String origin_str, old_str , new_str;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_t2);

            origin_str = "test example";
            old_str = "test";
            new_str = "etc";

            Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
            bt_create2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
                        if (!newFolder.exists()) {
                            newFolder.mkdir();
                        }

                        File file = new File(newFolder, "Test" + ".txt");
                        if (!file.exists()) {
                            file.createNewFile();
                            FileOutputStream fOut = new FileOutputStream(file);
                            OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
                            myOutWriter.append(origin_str);
                            myOutWriter.close();
                            fOut.close();
                        }
                    } catch (Exception e) {
                        System.out.println("e: " + e);
                    }
                }
            });

            Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
            bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
                        FileInputStream in = new FileInputStream(file);
                        int len = 0;
                        byte[] data1 = new byte[1024];
                        while ( -1 != (len = in.read(data1)) ){
                            if(new String(data1, 0, len).contains(old_str)){
                                String s = "";
                                s = s.replace(old_str, new_str);
                            }
                        }

                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }

                }
            });

使用这段代码,它是在 sdcard 上创建 Test.txt 并在上面写入 "test example"。
但是当用 "etc" 替换字符串 "test" 时,它不起作用。
如何解决?

我会给出我的代码,一直对我有用:)

希望对您有所帮助:DD

    public void saveString(String text){
            if(this.isExternalStorageAvailable()){
                if(!this.isExternalStorageReadOnly()){
                    try {
                        FileOutputStream fos = new FileOutputStream(
                                new File(this.getExternalFilesDir("text"), "text.dat"));
                        ObjectOutputStream oos = new ObjectOutputStream(fos);

                        oos.writeBytes(text);
                        oos.close();
                        fos.close();

                    } catch (FileNotFoundException e) {
                        //Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        //Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }

     private static boolean isExternalStorageAvailable(){
            String estadoSD = Environment.getExternalStorageState();
            if(Environment.MEDIA_MOUNTED.equals(estadoSD))
                return true;

            return false;
        }
        private static boolean isExternalStorageReadOnly(){
            String estadoSD = Environment.getExternalStorageState();
            if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
                return true;

            return false;
        }

public String getString(){
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        if(this.isExternalStorageAvailable()) {
            try {
                fis = new FileInputStream(
                        new File(this.getExternalFilesDir("text"), "text.dat"));
                ois = new ObjectInputStream(fis);

                String text = (String)ois.readObject();
                return familia;


            } catch (FileNotFoundException e) {
                //Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
            } catch (StreamCorruptedException e) {
                //Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
            } catch(EOFException e){
                try {
                    if(ois != null)
                        ois.close();

                    if(fis != null)
                        fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } catch (IOException e) {
                //Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
            } catch (ClassNotFoundException e) {
                //Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
            }
        }
        return null;
    }

试试这个

File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        line = line.replace(old,new);
    }
    br.close();

   FileOutputStream fOut = new FileOutputStream(file);
   OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
   myOutWriter.write(line);
   myOutWriter.close();
   fOut.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}