Android Studio - 为什么字符串数组导致我的程序停止?

时间:2015-04-06 23:51:13

标签: android arrays file-io crash android-widget

我一直在研究这个问题,我即将把头发拉出来! 如果我用这个......

public void readFile() {

        BufferedReader buffReader = null;
        StringBuilder result = new StringBuilder();
        try {
            FileInputStream fileIn = openFileInput("VariableStore.txt");
            buffReader = new BufferedReader(new InputStreamReader(fileIn));
            String line;
            while ((line = buffReader.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                assert buffReader != null;
                buffReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String resultString = result.toString();
        String[] controlString = resultString.split("$");
//        String wb = controlString[4];
//        String sb = controlString[5];

            ((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
//        ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
//        ((Button)this.findViewById(R.id.wakeButton)).setText(result);
//        ((Button)this.findViewById(R.id.wakeButton)).setText(result);
//        ((Button)this.findViewById(R.id.wakeButton)).setText(result);

    }

Button.setText适用于" resultString"或者用"结果"这是一个我输入格式为xxx $ xxx $ xxx $ xxx $ xxx的字符串,所以当我用readFile()读回来时,我想使用.Split并将它放入一个数组" controlString"然后将数组元素分配给我的小部件,即setText(controlString [0]);但如果我甚至取消注释线字符串wb = controlString [4];或String sb = controlString [5];我的程序崩溃了。为什么阵列元素不能在这里工作? 这是我的writeFile()....(完美无缺。

public void writeFile(){

BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();

String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;

try {
    FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
    buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
    try {
        buffWriter.write(writeString);
    } catch (IOException e) {
        e.printStackTrace();
    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
}finally {

    try {
        assert buffWriter != null;
        buffWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:-1)

我发现了问题...... 而不是:

String[] controlString = resultString.split("$");

我必须使用它:

String[] controlString = resultString.split(Pattern.quote("$"));