方法一:把目標文件放入resources文件中,以通過讀取R的資源文件來獲取,具體方式如下:
1、在res下新建raw文件,將帶讀取文件添加到raw文件目錄下。
2、添加如下代碼:
複製代碼
方法二:使用assets 只讀文件進行讀取。
1、將文件copy到assets下,可以新建文件夾如:“www”然後將文件放入www文件夾中,讀取的path爲:"www/filename"
複製代碼
以對象的方式讀取文件中的數據,如果沒有新建文件夾,把前面的“www/”去掉就ok啦
1、在res下新建raw文件,將帶讀取文件添加到raw文件目錄下。
2、添加如下代碼:
-
// 如果要使用文件名獲取文件數據:首先獲取資源id然後再通過id獲取輸入流
-
/** String fileName = fileName;
-
String packetName = context.getPackageName();
-
//將fileName 轉換成id
-
int resId = context.getResources().getIdentifier(fileName, "raw", packetName);
-
ObjectInputStream ois = null;
-
InputStream im = context.getResources().openRawResource(resId);
-
//其中getIdentifier三參數分別是:文件名,資源所在文件夾名(如:drawable, raw,),包路徑
-
-
*/
-
-
-
InputStream im = getResources().openRawResource(R.raw.h_data11);
-
BufferedReader read = new BufferedReader(new InputStreamReader(im));
-
String line = "";
-
StringBuilder sb = new StringBuilder();
-
try {
-
while((line = read.readLine()) != null) {
-
sb.append(line).append("\n");
-
}
-
} catch (IOException e) {
-
e.printStackTrace();
-
} finally {
-
if(read != null) {
-
try {
-
read.close();
-
read = null;
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
-
if(im != null) {
-
try {
-
im.close();
-
im = null;
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
- Log.v("", "result = " + sb.toString());
1、將文件copy到assets下,可以新建文件夾如:“www”然後將文件放入www文件夾中,讀取的path爲:"www/filename"
-
String result = "";
-
-
ObjectInputStream ois = null;
-
AssetManager am = context.getResources().getAssets();
-
try {
-
ois = new ObjectInputStream(am.open("www/filename"));
-
result = (String) ois.readObject();
-
} catch (StreamCorruptedException e) {
-
e.printStackTrace();
-
} catch (FileNotFoundException e) {
-
e.printStackTrace();
-
} catch (IOException e) {
-
e.printStackTrace();
-
} catch (ClassNotFoundException e) {
-
e.printStackTrace();
-
} finally {
-
try {
-
if (ois != null) {
-
ois.close();
-
ois = null;
-
}
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
- }