android 实现下载文件
/**
* 从网上下载
*@param url 下载路径
*@param outputFile 创建本地保存流的文件
*@return
* @return 下载失败返回1(比如没有网络等情况)下载成功返回0
*/
public static int downloadFile(String urlPsth, File outputFile) {
int result=0;
try {
URL url = new URL(urlPsth);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] bt = new byte[1024];
int i = 0;
while ((i = is.read(bt)) > 0) {
fos.write(bt, 0, i);
}
fos.flush();
fos.close();
is.close();
}else {
result=1;
}
} catch (FileNotFoundException e) {
result=1;
} catch (IOException e) {
result=1;
}
return result;
}
编程中文件读写是少不了的,如下:
读:
public String ReadSettings(Context context){
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String data = null;
try{
fIn = openFileInput("settings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
Toast.makeText(context, "Settings read",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
写:
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = openFileOutput("settings.dat",MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用方法:
WriteSettings(this,"setting0, setting1, setting2");
String data[] = ReadSettings(this).split(",");
在读取txt文件时,可能会遇到中文乱码情况,解决办法如下:
private String getTextString(String pathandname) throws IOException{
String str="";
FileInputStream fis = new FileInputStream(pathandname);
// InputStreamReader isr=new InputStreamReader(fis, "gbk");
// BufferedReader br=new BufferedReader(isr);
int size=fis.available();
byte[] buffer=new byte[size];
fis.read(buffer);
fis.close();
str = new String(buffer,"GBK");//支持双字节字符
myApp.setCharNumofString(str.length());//存储总字符数
return str;
}
读取assets文件夹下的txt文件
http://gundumw100.iteye.com/blog/850611