废话不多说,直接上代码,私有文件在data/data/appName/下,不能将文件拷贝
/**
* 将数据写入到私有文件中
* @param context
* @param data
* @param fileName
*/
private void saveDataToFile(Context context, String data, String fileName)
{
FileOutputStream fileOutputStream = null;
BufferedWriter bufferedWriter = null;
try
{
fileOutputStream = context.openFileOutput(fileName,
Context.MODE_APPEND);
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(data);
Toast.makeText(context, "存储的数据为"+data, Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (bufferedWriter != null)
{
bufferedWriter.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 从文件中读取数据
* @param context context
* @param fileName 文件名
* @return 从文件中读取的数据
*/
private String loadDataFromFile(Context context, String fileName)
{
FileInputStream fileInputStream = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try
{
/**
* 注意这里的fileName不要用绝对路径,只需要文件名就可以了,系统会自动到data目录下去加载这个文件
*/
fileInputStream = context.openFileInput(fileName);
bufferedReader = new BufferedReader(
new InputStreamReader(fileInputStream));
String result = "";
while ((result = bufferedReader.readLine()) != null)
{
stringBuilder.append(result);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return stringBuilder.toString();
}
以文本形式保存到指定文件夹可以进行拷贝
/**
* 将数据以文本的形式保存到指定目录下
* @param bytes
*/
private void saveToPublic(byte[] bytes){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)){
try{
String filename = newDate();
File file = new File(Environment.getExternalStorageDirectory()+"/"+"ZRY",filename);
if (!file.exists()){
File dir = new File(file.getParent());
dir.mkdirs();
}
FileOutputStream outStream = new FileOutputStream(file+".txt",true); //文件输出流用于将数据写入文件
outStream.write(bytes);
outStream.close(); //关闭文件输出流
}catch (Exception e){
e.printStackTrace();
}
}
}
/**
* 返回一个时间的名称
* @return
*/
public static String newDate(){
Time time = new Time();
time.setToNow();
int year = time.year;
int month = time.month+1;
int monthDay = time.monthDay;
int hour = time.hour;
int minute = time.minute;
int second = time.second;
return ""+year+month+monthDay+hour+minute+second;
}