我想在Android中读取SD卡中的文件,并替换掉其中的换行符,然后重新写入文件,以下是我用的方法:
public class FileOperationBase {
    int LENGTH = 1024;
    public void CreatFile(File file) {
        try {
            file.createNewFile();
            System.out.println("File is Created!");
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
    public void DeleteFile(File file) {
        if(file.exists())
            file.delete();
            System.out.println("File is Deleted!");
    }
    public void ReadFile(File file) {
        try {
            FileReader in = new FileReader(file);
            char[] byt = new char[LENGTH];
            int len=in.read(byt);
            System.out.println("*******"+len+"*******");
            System.out.println(new String(byt,0,len));
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void WriteFile(File file,String str) {
        try {
            FileWriter out= new FileWriter(file);
            out.write(str);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void ModifyFile(File file,String s1,String s2) {
        try {
            FileReader in = new FileReader(file);
            char[] byt = new char[LENGTH];
            int len=in.read(byt);
            String str1 = new String(byt);
            String str2 = str1.replace(s1, s2);
            WriteFile(file, str2);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
其中ReadFile是读取文件中的内容并输出,ModifyFile是将文件中的符号替换掉并调用WriteFile将替换后的字符串写入文件,最后再次调用ReadFile读出文件中的内容。
程序最后能够跑起来,但是有些问题。
如:test.txt是我自己写好内容后放到模拟器SD卡中去的,内容为:
abcd
abc
ab
a
第一次执行ReadFile指令后会正常显示并返回14个字符。但在执行ModifyFile以后程序显示如下:
“ abcdabcaba�����此处省略很多问好图标”
根据调试我知道时在ModifyFile方法中,char[]和string转化的问题,但具体不知道该如何解决,还望众高手帮忙支招。
另:如果用String s = "abcd\nabc\nab\na"来写入文档的话,读取字符串的长度编程了13,这又时为什么呢?