android实现文件读写功能
本文实例为大家分享了android实现文件读写功能的具体代码,供大家参考,具体内容如下
读取:
publicstaticString_getJsonString(StringfileName)
throwsIOException{
if((fileName==null)||fileName.isEmpty()){
return"";
}
StringretString="";
FileInputStreamfis=null;
Stringstate=Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
Filefile=newFile(Environment.getExternalStorageDirectory()
+"/"+fileName+".json");
if(file.exists()){
fis=newFileInputStream(file);
byte[]buffer=newbyte[fis.available()];
fis.read(buffer);
fis.close();
retString=newString(buffer);
}else{
}
}
returnretString;
}
写:
publicstaticvoidsaveSettingFile(StringfileName,Stringcontent){
FileOutputStreamfos=null;
Stringstate=Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
Filefile=newFile(Environment.getExternalStorageDirectory()
+"/"+fileName+".json");
try{
fos=newFileOutputStream(file);
byte[]buffer=content.getBytes();
fos.write(buffer);
fos.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
Gson读写:
publicstaticvoidsaveServerInfo(StringfileName,Stringcontent){
FileOutputStreamfos=null;
Stringstate=Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
Filefile=newFile(Environment.getExternalStorageDirectory()
+"/"+fileName+".json");
try{
fos=newFileOutputStream(file);
byte[]buffer=content.getBytes();
fos.write(buffer);
fos.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
publicstaticServerInfogetServerInfo(StringfileName)
throwsIOException{
ServerInfoserverInfo=newServerInfo();
if((fileName==null)||fileName.isEmpty()){
serverInfo=null;
returnserverInfo;
}
FileInputStreamfis=null;
Stringstate=Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
Filefile=newFile(Environment.getExternalStorageDirectory()
+"/"+fileName+".json");
if(file.exists()){
fis=newFileInputStream(file);
byte[]buffer=newbyte[fis.available()];
fis.read(buffer);
fis.close();
Gsongson=newGson();
serverInfo=gson.fromJson(newString(buffer),
ServerInfo.class);
}else{
serverInfo=null;
}
}
returnserverInfo;
}
调用:
publicvoidonSetIPAndPort(Viewview){
ServerInfoserverInfo=newServerInfo();
try{
serverInfo=JsonFileWriteAndRead.getServerInfo("videochat");
}catch(IOExceptione){
e.printStackTrace();
}
//写入ip和端口
Stringip=ipSet.getText().toString();
Stringport=portSet.getText().toString();
serverInfo.setIpString(ip);
serverInfo.setPortString(port);
Gsongson=newGson();
if(ip.isEmpty()||port.isEmpty()){
Toast.makeText(this,"地址或端口为空",Toast.LENGTH_SHORT).show();
}else{
JsonFileWriteAndRead.saveServerInfo("videochat",gson.toJson(serverInfo));
Toast.makeText(this,"地址和端口已经写入文件",Toast.LENGTH_SHORT).show();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。