編輯:關於Android編程
[java]
package com.xiazdong.file.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.os.Environment;
public class FileUtil {
/**
* 保存文本到內存
* @param context
* @param filename
* @param content
* @param mode
* @throws Exception
*/
public static void saveTextInMemory(Context context,String filename,String content,int mode) throws Exception{
try{
FileOutputStream out = context.openFileOutput(filename, mode);
out.write(content.getBytes("UTF-8"));
out.close();
}
catch(Exception e){
throw new Exception();
}
}
/**
* 保存文件到sdcard
* @param filename
* @param content
* @throws Exception
*/
public static void saveTextInSdcard(String filename,String content) throws Exception{
try{
File f = new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream out = new FileOutputStream(f);
out.write(content.getBytes("UTF-8"));
out.close();
}
catch(Exception e){
throw new Exception();
}
}
/**
* 從內存讀取文件
* @param filename
* @return
* @throws Exception
*/
public static String loadTextFromSdcard(String filename) throws Exception{
try{
File f = new File(Environment.getExternalStorageDirectory(),filename);
FileInputStream in = new FileInputStream(f);
byte[]data = read2byte(in);
return new String(data,"UTF-8");
}
catch(Exception e){
throw new Exception();
}
}
/**
* 從sdcard讀取文件
* @param context
* @param filename
* @return
* @throws Exception
*/
public static String loadTextFromMemory(Context context,String filename) throws Exception{
try{
FileInputStream in = context.openFileInput(filename);
byte[]data = read2byte(in);
return new String(data,"UTF-8");
}
catch(Exception e){
throw new Exception();
}
}
private static byte[] read2byte(InputStream in) throws IOException {
byte[] data;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[]buf = new byte[1024];
int len = 0;
while((len = in.read(buf))!=-1){
bout.write(buf, 0, len);
}
data = bout.toByteArray();
return data;
}
}
測試代碼:
[java]
FileUtil.saveTextInSdcard("1.txt","hello"); //將"hello"保存到/mnt/sdcard/1.txt中
String content = FileUtil.loadTextFromSdcard("1.txt"); //讀取/mnt/sdcard/1.txt內容
FileUtil.saveTextInMemory(MainActivity.this,"1.txt","hello", Context.MODE_PRIVATE); //將hello保存到/data/data/package/files/1.txt中
String content = FileUtil.loadTextFromMemory(MainActivity.this, "1.txt"); //讀取/data/data/package/files/1.txt內容
作者:xiazdong
Cocos2d-x 3.0 - Eclipse上構建一個Android項目2014年4月30日 4月末 本篇繼續介紹Cocos2d-x 3.0的一些基礎內容,前面一篇博客
上一篇博客,我們介紹了項目分包的結構,這一篇我們重點來介紹一下MVP架構在項目中的應用,MVP可以說是MVC模式的一種升級,在MVP出現之前,一般都是用MVC,但是使用M
一、Activity與Fragment之間通信1、Activity向Fragment傳值在Activity中使用setArguments封裝所需傳遞的值,在Fragmen
上周android推出了Android Support Library 23.2版本,提供了一些新的API支持和對現有庫增加新特性。先來看看Bottom Sheet這個控
status_t Camera::connectLegacy(int c