如何从本地test.txt文件中读取更新的数据?

时间:2018-01-15 11:05:33

标签: android read-data datawriter

我正在使用SliderLayout进行滑动图像。默认情况下,每隔10秒更改一次图像。如果用户想要更改时间间隔,请在设备本地内存中创建interval.txt文件并从该文件获取间隔时间。 现在我遇到的问题是,如果我在interval.txt中改变间隔时间,它会占用旧的时间间隔。 你能指导我,如何解决这个问题。

protected void onCreate(Bundle savedInstanceState) {
 writeFile();
 ImageSlider();
}
public void writeFile(){
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(txtFile));
        bw.write("10000");
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private void ImageSlider() {

    sliderLayout = (SliderLayout)findViewById(R.id.slider);
    File file=new File("Images/");
    File[] listFile = file.listFiles();
    for (File f: listFile) {
       .....
       .....
    }
    for(String name : Hash_file_maps.keySet()){
        TextSliderView textSliderView = new TextSliderView(MainActivity.this);
        ......
        ......
    }

        try {
            if ( new FileReader(txtFile) != null ) {
                BufferedReader bufferedReader = new BufferedReader(new FileReader(txtFile));
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }                   
                String ret = stringBuilder.toString();                 

sliderLayout.setDuration(Integer.parseInt(stringBuilder.toString()));
            }
        }
        } catch (IOException e) {
        }
    sliderLayout.addOnPageChangeListener(this);
}

2 个答案:

答案 0 :(得分:0)

您应该尝试使用Shared preferences而不是将值存储在文件中。

private final static String PREFS = "MY_SHARED_PREFERENCES";


private void storeDuration(Context context, int value) {
    SharedPreferences settings = context.getApplicationContext().getSharedPreferences(PREFS, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("DURATION", value);
    editor.apply();
}



private int getDuration(Context context) {
    SharedPreferences settings = context.getApplicationContext().getSharedPreferences(PREFS, 0);
    return settings.getInt("DURATION", 0);
}

答案 1 :(得分:0)

我已经解决了这个问题。

尝试{

        BufferedReader reader = new BufferedReader(new FileReader(txtFile));

        String line = "N/A";

        while ((line = reader.readLine()) != null) {
            text.append(line);
            duration = text.toString();

        }
        reader.close();
    } catch (IOException e) {

    }

sliderLayout.setDuration(Integer.valueOf(持续时间));