文件保存,String与int转换。
2019獨角獸企業重金招聘Python工程師標準>>>
public void yuyongfile(int num_insect) throws IOException {try {
FileOutputStream os = this.openFileOutput("yuyong.txt",
MODE_APPEND);
OutputStreamWriter outWriter = new OutputStreamWriter(os);
outWriter.write(num_insect);
//outWriter.write("\n");
outWriter.close();
// Toast.makeText(this, "成功寫入", 1).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "文件沒有找到", 1).show();
} catch (IOException e) {
e.printStackTrace();
}
}
其中,openFileOutput方法的第二個參數有很多方式,詳見
http://my.oschina.net/laigous/blog/29076
http://my.oschina.net/tcy901209/blog/101022
由于這種儲存方式是用流來存儲數據,故如果分次儲存到同一個文件時,取出來的時候會有麻煩。例如存數字。
方法:
存的時候以String存進去。用/當分隔符
拿出來的時候直接拿整個字符串,再Split開
存:
public void yuyongfile(String num_insect) throws IOException {
try {
FileOutputStream os = this.openFileOutput("yuyong.txt",
MODE_APPEND);
OutputStreamWriter outWriter = new OutputStreamWriter(os);
outWriter.write("/"+num_insect);
//outWriter.write("\n");
outWriter.close();
// Toast.makeText(this, "成功寫入", 1).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "文件沒有找到", 1).show();
} catch (IOException e) {
e.printStackTrace();
}
}
取:
public int[] aboutfile() throws IOException {
int[] num_insect=new int[100];
? ? ? ? String res="";
? ? ? ? String[] ins;
FileInputStream fin = openFileInput("yuyong.txt");
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
ins=res.split("/");
// Toast.makeText(context, ins.length+"int[0]:"+ins[0], Toast.LENGTH_SHORT).show();
for(int i=0;i<ins.length;i++){
num_insect[i]=Integer.parseInt(ins[i]);
}
fin.close();
return num_insect;
}
其中包含字符轉整形,整形轉字符。
轉載于:https://my.oschina.net/u/944946/blog/116092
總結
以上是生活随笔為你收集整理的文件保存,String与int转换。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 指定字符串按指定长度进行剪切
- 下一篇: ios学习记录 UITextField