1.文件操作工具类
/**
* 以文件流的方式复制文件
* @param src 文件源目录
* @param dest 文件目的目录
* @throws IOException
*/
public static void copyFile(String src,String dest) throws IOException{
FileInputStream in=new FileInputStream(src);
File file=new File(dest);
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c=in.read(buffer))!=-1){
for(int i=0;i<c;i++)
out.write(buffer[i]);
}
in.close();
out.close();
}
/**
* 利用PrintStream写文件
* @param src 写入文件的路径
*/
public static void PrintStreamOut(String src,String contents){
try {
FileOutputStream out=new FileOutputStream(src);
PrintStream p=new PrintStream(out);
for(int i=0;i<contents.length();i++)
p.print(contents.charAt(i));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 利用PrintStream写文件
* @param src 写入文件的路径
*/
public static void StringBufferOut(String src,String contents) throws IOException{
File file=new File(src);
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file,true);
for(int i=0;i<contents.length();i++){
StringBuffer sb=new StringBuffer();
sb.append(contents.charAt(i));
out.write(sb.toString().getBytes("utf-8"));
}
out.close();
}
/**
* 文件重命名
* @param path 文件目录
* @param oldname 原来的文件名
* @param newname 新文件名
* @param num 已存在该文件名
*/
public static void renameFile(String path,String oldname,String newname,int num,String suffix){
if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile=new File(path+"/"+oldname);
File newfile = null;
String temp = newname;
if(num==0){
newname = newname+suffix;
newfile=new File(path+"/"+newname);
}else{
newname = newname+num+suffix;
newfile=new File(path+"/"+newname);
}
if(newfile.exists()){//若在该目录下已经有一个文件和新文件名相同,则命名为newname1.2.3...
num++;
renameFile(path,oldname,temp,num,suffix);
}else{
oldfile.renameTo(newfile);
}
}
}
/**
* 转移文件目录
* @param filename 文件名
* @param oldpath 旧目录
* @param newpath 新目录
* @param cover 若新目录下存在和转移文件具有相同文件名的文件时,是否覆盖新目录下文件,cover=true将会覆盖原文件,否则不操作
*/
public static void changeDirectory(String filename,String oldpath,String newpath,boolean cover){
if(!oldpath.equals(newpath)){
File oldfile=new File(oldpath+"/"+filename);
File newfile=new File(newpath+"/"+filename);
if(newfile.exists()){//若在待转移目录下,已经存在待转移文件
if(cover){//覆盖
newfile.delete();
oldfile.renameTo(newfile);
}else
System.out.println("在新目录下已经存在:"+filename);
}
else{
oldfile.renameTo(newfile);
}
}
}
/**
* @author LiZhen
* @param strFile
* @throws Exception
*/
public static void UnZip(String strFile) throws Exception {
// 输出文件夹
String baseDir = "d:\";
ZipFile zFile = new ZipFile(strFile);
System.out.println(zFile.getName());
Enumeration en = zFile.entries();
ZipEntry entry = null;
while (en.hasMoreElements()) {
// 得到其中一项ZipEntry
entry = (ZipEntry) en.nextElement();
// 如果是文件夹则不处理
if (entry.isDirectory()) {
System.out.println("Dir: " + entry.getName() + " skipped..");
} else {
// 如果是文件则写到输出目录
copyFile(zFile, baseDir, entry);
}
}
zFile.close();
}
private static void copyFile(ZipFile source, String baseDir, ZipEntry entry)
throws Exception {
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
// 是否需要创建目录
mkdirs(baseDir, entry.getName());
// 建立输出流
OutputStream os = new BufferedOutputStream(new FileOutputStream(
new File(baseDir, entry.getName())));
// 取得对应ZipEntry的输入流
InputStream is = new BufferedInputStream(source.getInputStream(entry));
int readLen = 0;
byte[] buf = new byte[1024];
// 复制文件
System.out.println("Extracting: " + entry.getName() + "t"
+ entry.getSize() + "t" + entry.getCompressedSize());
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
System.out.println("Extracted: " + entry.getName());
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static void mkdirs(String baseDir, String relativeFileName) {
String[] dirs = relativeFileName.split("/");
File ret = new File(baseDir);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
}
2.Bitmap与DrawAble与byte[]与InputStream之间的转换工具类
package com.soai.imdemo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
/**
* Bitmap与DrawAble与byte[]与InputStream之间的转换工具类
* @author Administrator
*
*/
public class FormatTools {
private static FormatTools tools = new FormatTools();
public static FormatTools getInstance() {
if (tools == null) {
tools = new FormatTools();
return tools;
}
return tools;
}
// 将byte[]转换成InputStream
public InputStream Byte2InputStream(byte[] b) {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
return bais;
}
// 将InputStream转换成byte[]
public byte[] InputStream2Bytes(InputStream is) {
String str = "";
byte[] readByte = new byte[1024];
int readCount = -1;
try {
while ((readCount = is.read(readByte, 0, 1024)) != -1) {
str += new String(readByte).trim();
}
return str.getBytes();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 将Bitmap转换成InputStream
public InputStream Bitmap2InputStream(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
// 将Bitmap转换成InputStream
public InputStream Bitmap2InputStream(Bitmap bm, int quality) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
// 将InputStream转换成Bitmap
public Bitmap InputStream2Bitmap(InputStream is) {
return BitmapFactory.decodeStream(is);
}
// Drawable转换成InputStream
public InputStream Drawable2InputStream(Drawable d) {
Bitmap bitmap = this.drawable2Bitmap(d);
return this.Bitmap2InputStream(bitmap);
}
// InputStream转换成Drawable
public Drawable InputStream2Drawable(InputStream is) {
Bitmap bitmap = this.InputStream2Bitmap(is);
return this.bitmap2Drawable(bitmap);
}
// Drawable转换成byte[]
public byte[] Drawable2Bytes(Drawable d) {
Bitmap bitmap = this.drawable2Bitmap(d);
return this.Bitmap2Bytes(bitmap);
}
// byte[]转换成Drawable
public Drawable Bytes2Drawable(byte[] b) {
Bitmap bitmap = this.Bytes2Bitmap(b);
return this.bitmap2Drawable(bitmap);
}
// Bitmap转换成byte[]
public byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
// byte[]转换成Bitmap
public Bitmap Bytes2Bitmap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
return null;
}
// Drawable转换成Bitmap
public Bitmap drawable2Bitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
// Bitmap转换成Drawable
public Drawable bitmap2Drawable(Bitmap bitmap) {
BitmapDrawable bd = new BitmapDrawable(bitmap);
Drawable d = (Drawable) bd;
return d;
}
}
3.其它常用工具类
一. 检查网络是否可用.
ConnectionUtil.java
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- public class ConnectionUtil {
- /**
- * 检查网络是否可用
- * @param context
- 应用程序的上下文对象
- * @return
- */
- public static boolean isNetworkAvailable(Context context) {
- ConnectivityManager connectivity = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- //获取系统网络连接管理器
- if (connectivity == null) {
- //如果网络管理器为null
- return false; //返回false表明网络无法连接
- } else {
- NetworkInfo[] info = connectivity.getAllNetworkInfo();
- //获取所有的网络连接对象
- if (info != null) {
- //网络信息不为null时
- for (int i = 0; i < info.length; i++) {
- //遍历网路连接对象
- if (info[i].isConnected()) {
- //当有一个网络连接对象连接上网络时
- return true; //返回true表明网络连接正常
- }
- }
- }
- }
- return false;
- }
- public static void httpTest(final Context ctx,String title,String msg) {
- if (!isNetworkAvailable(ctx)) {
- AlertDialog.Builder builders = new AlertDialog.Builder(ctx);
- builders.setTitle(title);
- builders.setMessage(msg);
- builders.setPositiveButton(android.R.string.ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- //alert.dismiss();
- }
- });
- AlertDialog alert = builders.create();
- alert.show();
- }
- }
- }
FileStreamTool.java
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.PushbackInputStream;
- public class FileStreamTool {
- public static void save(File file, byte[] data) throws Exception {
- FileOutputStream outStream = new FileOutputStream(file);
- outStream.write(data);
- outStream.close();
- }
- public static String readLine(PushbackInputStream in) throws IOException {
- char buf[] = new char[128];
- int room = buf.length;
- int offset = 0;
- int c;
- loop: while (true) {
- switch (c = in.read()) {
- case -1:
- case '\n':
- break loop;
- case '\r':
- int c2 = in.read();
- if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
- break loop;
- default:
- if (--room < 0) {
- char[] lineBuffer = buf;
- buf = new char[offset + 128];
- room = buf.length - offset - 1;
- System.arraycopy(lineBuffer, 0, buf, 0, offset);
- }
- buf[offset++] = (char) c;
- break;
- }
- }
- if ((c == -1) && (offset == 0)) return null;
- return String.copyValueOf(buf, 0, offset);
- }
- /**
- * 读取流
- * @param inStream
- * @return 字节数组
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while( (len=inStream.read(buffer)) != -1){
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
三.文件断点续传.
MainActivity.java
- import java.io.File;
- import java.io.OutputStream;
- import java.io.PushbackInputStream;
- import java.io.RandomAccessFile;
- import java.net.Socket;
- import cn.itcast.service.UploadLogService;
- import cn.itcast.utils.StreamTool;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Environment;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- private EditText filenameText;
- private TextView resultView;
- private ProgressBar uploadbar;
- private UploadLogService service;
- private Handler handler = new Handler(){
- @Override
- public void handleMessage(Message msg) {
- uploadbar.setProgress(msg.getData().getInt("length"));
- float num = (float)uploadbar.getProgress() / (float)uploadbar.getMax();
- int result = (int)(num * 100);
- resultView.setText(result + "%");
- if(uploadbar.getProgress() == uploadbar.getMax()){
- Toast.makeText(MainActivity.this, R.string.success, 1).show();
- }
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- service = new UploadLogService(this);
- filenameText = (EditText)findViewById(R.id.filename);
- resultView = (TextView)findViewById(R.id.result);
- uploadbar = (ProgressBar)findViewById(R.id.uploadbar);
- Button button = (Button)findViewById(R.id.button);
- button.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- String filename = filenameText.getText().toString();
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- File file = new File(Environment.getExternalStorageDirectory(), filename);
- if(file.exists()){
- uploadbar.setMax((int)file.length());
- uploadFile(file);
- }else{
- Toast.makeText(MainActivity.this, R.string.notexsit, 1).show();
- }
- }else{
- Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();
- }
- }
- });
- }
- private void uploadFile(final File file) {
- new Thread(new Runnable() {
- public void run() {
- try {
- String sourceid = service.getBindId(file);
- Socket socket = new Socket("192.168.1.100", 7878);//根据IP地址和端口不同更改
- OutputStream outStream = socket.getOutputStream();
- String head = "Content-Length="+ file.length() + ";filename="+ file.getName()
- + ";sourceid="+(sourceid!=null ? sourceid : "")+"\r\n";
- outStream.write(head.getBytes());
- PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
- String response = StreamTool.readLine(inStream);
- String[] items = response.split(";");
- String responseSourceid = items[0].substring(items[0].indexOf("=")+1);
- String position = items[1].substring(items[1].indexOf("=")+1);
- if(sourceid==null){ //如果是第一次上传文件,在数据库中不存在该文件所绑定的资源id,入库
- service.save(responseSourceid, file);
- }
- RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");
- fileOutStream.seek(Integer.valueOf(position));
- byte[] buffer = new byte[1024];
- int len = -1;
- int length = Integer.valueOf(position);
- while( (len = fileOutStream.read(buffer)) != -1){
- outStream.write(buffer, 0, len);
- length += len;//累加已经上传的数据长度
- Message msg = new Message();
- msg.getData().putInt("length", length);
- handler.sendMessage(msg);
- }
- if(length == file.length()) service.delete(file);
- fileOutStream.close();
- outStream.close();
- inStream.close();
- socket.close();
- } catch (Exception e) {
- Toast.makeText(MainActivity.this, R.string.error, 1).show();
- }
- }
- }).start();
- }
- }
DBOpenHelper.java
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;