100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > android文件读取文件内容 android创建txt文件 读取txt文件内容

android文件读取文件内容 android创建txt文件 读取txt文件内容

时间:2018-10-19 09:08:55

相关推荐

android文件读取文件内容 android创建txt文件 读取txt文件内容

1.android在sd卡上创建一个txt文件,并且写入内容:

public static boolean saveTxt(String phoneNumber,Context context,String path){

//sd卡检测

String sdStatus = Environment.getExternalStorageState();

if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){

Toast.makeText(context, "SD 卡不可用", Toast.LENGTH_SHORT).show();

return false;

}

//检测文件夹是否存在

File file = new File(path);

file.exists();

file.mkdirs();

String p = path+File.separator+"1.txt";

FileOutputStream outputStream = null;

try {

//创建文件,并写入内容

outputStream = new FileOutputStream(new File(p));

String msg = new String(phoneNumber);

outputStream.write(msg.getBytes("UTF-8"));

} catch (FileNotFoundException e) {

e.printStackTrace();

return false;

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(outputStream!=null){

try {

outputStream.flush();

} catch (IOException e) {

e.printStackTrace();

}

try {

outputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return true;

}

2.读取txt内容

public static String readPhoneNumber(String path){

byte Buffer[] = new byte[1024];

//得到文件输入流

File file = new File(path+File.separator+"1.txt");

FileInputStream in = null;

ByteArrayOutputStream outputStream = null;

try {

in = new FileInputStream(file);

//读出来的数据首先放入缓冲区,满了之后再写到字符输出流中

int len = in.read(Buffer);

//创建一个字节数组输出流

outputStream = new ByteArrayOutputStream();

outputStream.write(Buffer,0,len);

//把字节输出流转String

return new String(outputStream.toByteArray());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(in!=null){

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(outputStream!=null){

try {

outputStream.flush();

outputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return null;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。