Android常用工具類2

來源:互聯網
上載者:User

讀取流檔案

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()});
}
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.