編輯:關於Android編程
在局域網內,實現從android客戶端把手機SD卡上的文件上傳到PC服務器端,並保存在PC硬盤的指定文件夾下。同時把PC端硬盤文件的目錄和對文件的描述信息保存在mysql數據庫中。
1、客戶端關鍵代碼:
(1)獲得SD卡上的文件
/**
* 獲得文件路徑和狀態信息
*
* @return
*/
private String getFiles() {
File path = null;
// 判斷SD卡是否存在可用
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory();
File[] files = path.listFiles();
for (File file : files) {
// 把路徑如入集合中
if (file.getPath() != null
&& (file.getPath()
.substring(file.getPath().lastIndexOf("/") + 1)
.equals("DATA_RECORD.pcm"))) {
return file.getPath();
}
}
} else {
Toast.makeText(ASRMainActivity.this, "SD卡不可用!", 300).show();
}
return null;
}private void fileUpLoad() {
srcPath=getFiles();
new AsyncTask() {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "****************";
HttpURLConnection con;
URL url = null;
InputStreamReader isr = null;
FileInputStream fis;
DataOutputStream dos;
@Override
protected Void doInBackground(Void... params) {
String record_content=mSharedPreferences.getString("content","");
Log.i("測試",record_content);
try {
// 首先指定服務器的路徑URL
url = new URL(
"http://192.168.1.109:8080/MFCC/SpeechRecognizeAction?action_flag=upload&record_content="+record_content);
// 打開一個連接
con = (HttpURLConnection) url.openConnection();
// 設置一些屬性
con.setDoInput(true);
con.setDoOutput(true);
con.setDefaultUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
con.setReadTimeout(3000);
//
// 創建一個新的數據輸出流,將數據寫入指定基礎輸出流
dos = new DataOutputStream(con.getOutputStream());
// 將字符串按字節順序 寫出 到基礎輸出流中
// dos.writeBytes("Content-Disposition: form-data; name=\"uploads\";filename=1.txt");
// dos.writeBytes("Content-Disposition: form-data;");
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\"" + end);
Log.i("tag",
"Content-Disposition: form-data; name=\"file\"; filename=\""
+ srcPath.substring(srcPath
.lastIndexOf("/") + 1) + "\"" + end);
dos.writeBytes(end);
// dos.writeBytes("1.txt");
// dos.writeBytes("Jonny-Resume.docx");
// 讀取寫到輸出流中的數據
fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
count = fis.read(buffer);
Log.i("tag", count + " ********************");
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
Log.i("tag", "ok");
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
// 反饋給客戶端的信息
InputStream is = con.getInputStream();
isr = new InputStreamReader(is, "utf-8");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
String result2 = null;
StringBuffer stringBuffer = null;
BufferedReader br = null;
if (isr == null) {
return;
}
try {
br = new BufferedReader(isr);
stringBuffer = new StringBuffer();
while ((result2 = br.readLine()) != null) {
stringBuffer.append(result2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (stringBuffer != null)
Toast.makeText(ASRMainActivity.this,
new String(stringBuffer), Toast.LENGTH_LONG).show();
btn_uploadFile.setEnabled(true);
}
}.execute();
} /**
* 上傳文件到PC,並把相關的文件信息寫如數據庫
* @param request
* @param response
*/
private void uploadFile(HttpServletRequest request, HttpServletResponse response) {
String content = request.getParameter("record_content");
PrintWriter printWriter=null;
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();// 實例化一個文件工廠
// 構建一個文件上傳類
ServletFileUpload servletFileUpload = new ServletFileUpload(
diskFileItemFactory);// 生成一個處理文件上傳的servlet對象
servletFileUpload.setFileSizeMax(3 * 1024 * 1024);
servletFileUpload.setSizeMax(6 * 1024 * 1024);// 上傳文件總大小
try {
// 分析請求,並得到上傳文件的FileItem對象
printWriter=response.getWriter();
List items = servletFileUpload.parseRequest(request);
Iterator e = items.iterator();
while (e.hasNext()) {
FileItem item = e.next();
if (item.getName() != null && !item.getName().equals("")) {
File file = new File("E://rawSpeechRecordData//");
File newFile = null;
if (!file.exists()) {
file.mkdir();
if (file.isDirectory()) {
SimpleDateFormat format = new SimpleDateFormat(
"yyyyMMddHHmmss");
String date = format.format(new Date(System
.currentTimeMillis()));
newFile = new File(
"E://rawSpeechRecordData//rawdata" + date
+".pcm");
item.write(newFile);
//數據存入數據庫
System.out.println("**********************"
+ newFile.getPath());
mFileInfoDao.addFilePathInfos(newFile.getPath(), content);
printWriter.write("數據提交成功!");
System.out.println(file);
System.out
.println("Content-Disposition: form-data; name=\"file\"; filename=\"");
System.out.println("**********************");
}
} else {
if (file.isDirectory()) {
SimpleDateFormat format = new SimpleDateFormat(
"yyyyMMddHHmmss");
String date = format.format(new Date(System
.currentTimeMillis()));
newFile = new File(
"E://rawSpeechRecordData//rawdata" + date
+".pcm");
item.write(newFile);
//數據存入數據庫
mFileInfoDao.addFilePathInfos(newFile.getPath(), content);
printWriter.write("數據提交成功!");
System.out.println("**********************"
+ newFile.getPath());
System.out.println(file);
System.out
.println("Content-Disposition: form-data; name=\"file\"; filename=\"");
System.out.println("**********************");
}
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
(1)數據庫操作接口定義
public interface FileInfoDao {
/**
* 添加文件路徑到數據庫
* @param filePath 文件路徑
* @param content錄音的詳細信息
*/
public void addFilePathInfos(String filePath,String content);
/**
* 刪除一條錄音的路徑信息
* @param content 錄音的詳細信息
*/
public void deleteAFilePathInfo(String content);
/**
* 刪除所有的錄音文件路徑
*/
public void deleteAllFilePathInfos();
/**
* 查詢所有的文件路徑
* @return
*/
public Listpublic class FileInfoDaoimpl implements FileInfoDao {
// 表示定義數據庫的用戶名
private final String USERNAME = "root";
// 定義數據庫的密碼
private final String PASSWORD = "admin";
// 定義數據庫的驅動信息
private final static String DRIVER = "com.mysql.jdbc.Driver";
// 定義數據庫連接
private static Connection mConnection;
// 定義訪問數據庫的地址
private final String URL = "jdbc:mysql://192.168.1.109:3306/fileinfos";
// 定義sql語句的執行對象
private PreparedStatement pstmt;
// 定義查詢返回的結果集合
private ResultSet resultSet;
public FileInfoDaoimpl() {
// 加載驅動
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void addFilePathInfos(String filePath, String content) {
PreparedStatement preparedStatement = null;
try {
// 獲得數據庫連接
mConnection = DriverManager.getConnection(URL, "root", "admin");
// 獲得SQL語句執行對象
preparedStatement = mConnection
.prepareStatement("insert into filepaths(file_path,record_content) values(?,?)");
// 設置參數
preparedStatement.setString(1, filePath);
preparedStatement.setString(2, content);
// 執行SQL語句
preparedStatement.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
preparedStatement = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (mConnection != null) {
try {
mConnection.close();
mConnection = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void deleteAFilePathInfo(String content) {
PreparedStatement preparedStatement=null;
//獲得數據庫連接
try {
mConnection=DriverManager.getConnection(URL,"root","admin");
//獲得SQL語句執行對象
preparedStatement=mConnection.prepareStatement("delete from filepaths where record_content=?");
//設置參數
preparedStatement.setString(1, content);
preparedStatement.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(preparedStatement!=null){
try {
preparedStatement.close();
preparedStatement=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(mConnection!=null){
try {
mConnection.close();
mConnection=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void deleteAllFilePathInfos() {
PreparedStatement preparedStatement=null;
try {
mConnection=DriverManager.getConnection(URL, USERNAME,PASSWORD);
preparedStatement=mConnection.prepareStatement("delete from filepaths");
preparedStatement.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(preparedStatement!=null){
try {
preparedStatement.close();
preparedStatement=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(mConnection!=null){
try {
mConnection.close();
mConnection=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public Listpublic class FilePathInfosDaoFactory {
private static FileInfoDao mFileInfoDaoimpl;
/**
* 獲得數據庫操作單例對象
*
* @return
*/
public static FileInfoDao getInstanse() {
if (mFileInfoDaoimpl == null) {
mFileInfoDaoimpl = new FileInfoDaoimpl();
}
return mFileInfoDaoimpl;
}
}
android 自定義標題欄
用到的兩個png圖片首先是自定義theme,不能用默認的主題,會報錯;you cannot combined....。修改res/values/styles.xml:上面
Android之斷點續傳下載
今天學習了Android開發中比較難的一個環節,就是斷點續傳下載,很多人看到這個標題就感覺頭大,的確,如果沒有良好的邏輯思維,這塊的確很難搞明白。下面我就將自己學到的知
Android應用開發SharedPreferences存儲數據的使用方法
SharedPreferences是Android中最容易理解的數據存儲技術,實際上SharedPreferences處理的就是一個key-value(鍵值對)。Shar
Android自定義View之自定義評價打分控件RatingBar實現自定義星星大小和間距
在Android開發中,我們經常會用到對商家或者商品的評價,運用星星進行打分。然而在Android系統中自帶的打分控件,RatingBar特別不好用,間距和大小無法改變。