我目前正在开发一个查找越来越大质数的应用。当找到新的素数时,它将被保存到文件中。仅需要存储最后找到的素数。用户应该能够查看此素数。应用启动后,它将继续查看关闭时的状态。
但是我在寻找一种方法来将素数保存到文件时遇到问题?
public class MainActivity extends AppCompatActivity {
Button b;
int max = 500;
TextView vTextView;
int j = 2;
Button S;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
vTextView = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
vTextView.setText(i+"");
j = i+1;
break;
}
}
}
});
}
public boolean isPrimeNumber(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
答案 0 :(得分:0)
用于写入文件:
public void writeToFile(String dataToWrite) {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir() + File.separator + "MyFile.txt")));
bufferedWriter.write(dataToWrite);
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
要从文件中读取:
public String readFromFile() {
StringBuilder builder = new StringBuilder("");
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir() + File.separator + "MyFile.txt")));
String read;
while ((read = bufferedReader.readLine()) != null) {
builder.append(read);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
答案 1 :(得分:0)
如果可以使用SharedPreferences
,则可以这样操作:
如何阅读SharedPreferences
SharedPreferences prefs = getApplicationContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
int index = prefs.getInt("file_index", 0);
如何编写SharedPreferences
SharedPreferences prefs = getApplicationContext().getSharedPreferences("preferences", Context.MODE_PRIVATE);
prefs.edit().putInt("file_index", index).commit();
请注意,创建静态字符串比使用硬编码字符串更好。
有关SharedPreferences的更多详细信息:https://developer.android.com/training/data-storage/shared-preferences