Android常用工具类

来源:互联网 发布:日本js蓝光眼镜 编辑:程序博客网 时间:2024/06/04 18:37

Android常用工具类

分类: Android 107人阅读 评论(0)收藏 举报
读取流文件

StreamTool.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 StreamTool {


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;


public class DBOpenHelper extends SQLiteOpenHelper {


public DBOpenHelper(Context context) {
super(context, "itcast.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}

}


UploadLogService.java


import java.io.File;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


public class UploadLogService {
private DBOpenHelper dbOpenHelper;

public UploadLogService(Context context){
dbOpenHelper = new DBOpenHelper(context);
}

public String getBindId(File file){
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select sourceid from uploadlog where path=?", new String[]{file.getAbsolutePath()});
if(cursor.moveToFirst()){
return cursor.getString(0);
}
return null;
}

public void save(String sourceid, File file){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("insert into uploadlog(path,sourceid) values(?,?)",
new Object[]{file.getAbsolutePath(), sourceid});
}

public void delete(File file){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("delete from uploadlog where path=?", new Object[]{file.getAbsolutePath()});
}
}

0 0