編輯:Android開發實例
一、簡單版
代碼如下:
import java.io.FileInputStream;
void readFileOnLine(){
String strFileName = "Filename.txt";
FileInputStream fis = openFileInput(strFileName);
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
while((strLine = dataIO.readLine()) != null) {
sBuffer.append(strLine + “\n");
}
dataIO.close();
fis.close();
}
二、簡潔版
代碼如下:
//讀取文本文件中的內容
public static String ReadTxtFile(String strFilePath)
{
String path = strFilePath;
String content = ""; //文件內容字符串
//打開文件
File file = new File(path);
//如果path是傳遞過來的參數,可以做一個非目錄的判斷
if (file.isDirectory())
{
Log.d("TestFile", "The File doesn't not exist.");
}
else
{
try {
InputStream instream = new FileInputStream(file);
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行讀取
while (( line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();
}
}
catch (java.io.FileNotFoundException e)
{
Log.d("TestFile", "The File doesn't not exist.");
}
catch (IOException e)
{
Log.d("TestFile", e.getMessage());
}
}
return content;
}
三、用於長時間使用的apk,並且有規律性的數據
1,逐行讀取文件內容
代碼如下:
//首先定義一個數據類型,用於保存讀取文件的內容
class WeightRecord {
String timestamp;
float weight;
public WeightRecord(String timestamp, float weight) {
this.timestamp = timestamp;
this.weight = weight;
}
}
//開始讀取
private WeightRecord[] readLog() throws Exception {
ArrayList<WeightRecord> result = new ArrayList<WeightRecord>();
File root = Environment.getExternalStorageDirectory();
if (root == null)
throw new Exception("external storage dir not found");
//首先找到文件
File weightLogFile = new File(root,WeightService.LOGFILEPATH);
if (!weightLogFile.exists())
throw new Exception("logfile '"+weightLogFile+"' not found");
if (!weightLogFile.canRead())
throw new Exception("logfile '"+weightLogFile+"' not readable");
long modtime = weightLogFile.lastModified();
if (modtime == lastRecordFileModtime)
return lastLog;
// file exists, is readable, and is recently modified -- reread it.
lastRecordFileModtime = modtime;
// 然後將文件轉化成字節流讀取
FileReader reader = new FileReader(weightLogFile);
BufferedReader in = new BufferedReader(reader);
long currentTime = -1;
//逐行讀取
String line = in.readLine();
while (line != null) {
WeightRecord rec = parseLine(line);
if (rec == null)
Log.e(TAG, "could not parse line: '"+line+"'");
else if (Long.parseLong(rec.timestamp) < currentTime)
Log.e(TAG, "ignoring '"+line+"' since it's older than prev log line");
else {
Log.i(TAG,"line="+rec);
result.add(rec);
currentTime = Long.parseLong(rec.timestamp);
}
line = in.readLine();
}
in.close();
lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
return lastLog;
}
//解析每一行
private WeightRecord parseLine(String line) {
if (line == null)
return null;
String[] split = line.split("[;]");
if (split.length < 2)
return null;
if (split[0].equals("Date"))
return null;
try {
String timestamp =(split[0]);
float weight = Float.parseFloat(split[1]) ;
return new WeightRecord(timestamp,weight);
}
catch (Exception e) {
Log.e(TAG,"Invalid format in line '"+line+"'");
return null;
}
}
2,保存為文件
代碼如下:
public boolean logWeight(Intent batteryChangeIntent) {
Log.i(TAG, "logBattery");
if (batteryChangeIntent == null)
return false;
try {
FileWriter out = null;
if (mWeightLogFile != null) {
try {
out = new FileWriter(mWeightLogFile, true);
}
catch (Exception e) {}
}
if (out == null) {
File root = Environment.getExternalStorageDirectory();
if (root == null)
throw new Exception("external storage dir not found");
mWeightLogFile = new File(root,WeightService.LOGFILEPATH);
boolean fileExists = mWeightLogFile.exists();
if (!fileExists) {
if(!mWeightLogFile.getParentFile().mkdirs()){
Toast.makeText(this, "create file failed", Toast.LENGTH_SHORT).show();
}
mWeightLogFile.createNewFile();
}
if (!mWeightLogFile.exists()) {
Log.i(TAG, "out = null");
throw new Exception("creation of file '"+mWeightLogFile.toString()+"' failed");
}
if (!mWeightLogFile.canWrite())
throw new Exception("file '"+mWeightLogFile.toString()+"' is not writable");
out = new FileWriter(mWeightLogFile, true);
if (!fileExists) {
String header = createHeadLine();
out.write(header);
out.write('\n');
}
}
Log.i(TAG, "out != null");
String extras = createBatteryInfoLine(batteryChangeIntent);
out.write(extras);
out.write('\n');
out.flush();
out.close();
return true;
} catch (Exception e) {
Log.e(TAG,e.getMessage(),e);
return false;
}
}
登錄應用程序的屏幕,詢問憑據登錄到一些特定的應用。可能需要登錄到Facebook,微博等本章介紹了,如何創建一個登錄界面,以及如何管理安全問題和錯誤嘗試。首先,必須定義兩
JSON代表JavaScript對象符號。它是一個獨立的數據交換格式,是XML的最佳替代品。本章介紹了如何解析JSON文件,並從中提取所需的信息。Android提供了四個
Android應用程序可以在許多不同地區的許多設備上運行。為了使應用程序更具交互性,應用程序應該處理以適合應用程序將要使用的語言環境方面的文字,數字,文件等。在本章中,我
前言 本文主要介紹在Android中怎樣來解析XML文件。主要采用的是SAX機制,SAX全稱為Simple API for XML,它既是一種