編輯:關於Android編程
說明:
文件保存路徑為安卓默認路徑,/data/應用包名(全名)/files
一、activity
package com.example.filerw;
import com.example.server.FileServer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText contentEdit;
private String file_name=file.txt;
private FileServer fileServer;
private TextView showText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentEdit = (EditText)findViewById(R.id.content);
showText = (TextView)findViewById(R.id.showText);
fileServer = new FileServer(getApplicationContext());
}
public void MainClick(View v){
switch (v.getId()) {
case R.id.save:
String str = contentEdit.getText().toString();
fileServer.save(file_name, str);
break;
case R.id.read:
String show = fileServer.read(file_name);
showText.setText(show);
break;
default:
break;
}
}
//菜單
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
二、主要實現代碼
package com.example.server;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.http.util.EncodingUtils;
import android.content.Context;
public class FileServer {
private Context context;
private FileInputStream in;
private FileOutputStream out;
public FileServer(Context context){
this.context = context;
}
/**
* 保存
* @param name
*/
public void save(String name,String content){
try {
out = context.openFileOutput(name, Context.MODE_PRIVATE);
out.write(content.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println(e.toString());
}
}
/**
* 讀文件
* @param name
* @return
*/
public String read(String name){
String file_content = null;
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
in = context.openFileInput(name);//具有緩沖實例的打開文件
byte[] buf = new byte[1024];
while((in.read(buf))!=-1){
byteOut.write(buf);//將讀出來的數據寫到緩存中
}
file_content = EncodingUtils.getString(byteOut.toByteArray(),GBK);//轉碼
byteOut.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
System.out.println(e.toString());
}
return file_content;
}
}
//
使用SignalR推送服務在Android的實現 SignalA
由於我的版本最低是2.2,所以只有把源碼下下來自己改,如果你覺得太多了可自己編譯成jar引用,本人不才,對java不是很熟悉,如果此版本中有錯誤還請大家指出來,此圖顯示的
android產品研發(二十)--)代碼Review
上一篇文章中我們講解了如何在android studio中進行單元測試。實際開發過程中有一些功能性的需求,比如測試工具類,測試數據存儲等測試工作,如果還是通過重復執行ap
Android自定義Chronometer實現短信驗證碼秒表倒計時功能
本文實例為大家分享了Chronometer實現倒計時功能,Android提供了實現按照秒計時的API,供大家參考,具體內容如下一、自定義ChronometerView 繼
Android RxJava使用介紹(四) RxJava的操作符
本篇文章繼續介紹以下類型的操作符Observable Utility Operators(Observable的功能性操作符) Conditional and Boole