我想将 8 个整数存储到 .csv 文件中(文件名将作为 EditText 的输入)并在需要时检索它们。
要获取文件名,您可以使用:
EditText fileNameEdit= (EditText) getActivity().findViewById(R.id.fileName);
String fileName = fileNameEdit.getText().toString();
Run Code Online (Sandbox Code Playgroud)
然后将文件写入磁盘:
try {
String content = "Separe here integers by semi-colon";
File file = new File(fileName +".csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
要读取文件:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName+".csv"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
然后要拥有整数,您可以使用拆分功能:
String[] intArray = sCurrentLine.split(";");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15327 次 |
| 最近记录: |