如何获取android 下的StreamingAssets文件夹中的xml文件

如何获取android 下的StreamingAssets文件夹中的xml文件,第1张

assets文件夹里面的文件都是保持原始的文件格式,需要用AssetManager以字节流的形式读取文件。

assets的读取方式:

1 先在Activity里面调用getAssets() 来获取AssetManager引用。

2 再用AssetManager的open(String fileName, int accessMode) 方法则指定读取的文件以及访问模式就能得到输入流InputStream。

3 然后就是用已经open file 的inputStream读取文件,读取完成后记得inputStreamclose() 。

4调用AssetManagerclose() 关闭AssetManager。

需要注意的是,来自Resources和Assets 中的文件只可以读取而不能进行写的 *** 作

首先看看刚创建完的项目界面,除了菜单栏、工具栏等,没有什么可以编辑的界面

通过项目的文件浏览器可以打开所有项目文件,所以文件管理器在整个开发过程中相当重要。

其中用到最多的便是app项,其余大部分是软件自动执行或生成相关文件;

External libraries用来保存外部导入的类库,用到的时候可以进行调用。

在app项下面包含了项目创建所需的资源和配置文件:

首先打开layout,在src-》main-》res-》layout下,这是安卓app的界面设计文件,所有的界面都可以通过这里的xml文件生成

双击xml文件打开设计界面,关于layout的具体设计以后再讲,这里仅介绍如何打开layout。

项目的菜单设计在menu项下的xml文件中定义和设计。

字符串文件也是项目中重要的文件,在app开发过程中会用到很多字符串数据,建议大家都在stringsxml中定义好以后再调用,这样在汉化或者转化为他国语言时,只要备份stringsxml文件,然后替换成中文或他国文字就可以了。其实这就是其他国家软件汉化成中文的途径。

软件图标的设计也是非常重要的,这就是UI设计的目的所在,所有文件都应保存在drawable-xxxx文件下

另外一个重要文件就是AndroidManifestxml,这里定义了项目的打包名称;项目的标题、主题、图标以及所有的活动项,各种访问权限的设置等等都在这里设置。

接下来是安卓开发最重要的部分,活动程序的编写部分,所有app都至少包含一个activity,这里用来实现app所需的功能,完成功能代码的编写,这里可以调用其他文件中定义的资源对界面进行访问,对接收器或发生器进行读写等等

最后讲讲R文件,R文件在app->build->source->r->debug下的第二个文件夹下,用来存放所有activity、layout、控件等资源的定义,这是软件自动生成的,不需要修改也不允许修改,在编程过程中一般通过Ridxxx来访问资源。

1 用Java包给应用程序命名。这个包名是应用程序的唯一标识;

2 描述应用程序的组件---组成应用程序的Activity、Service、Broadcast Receiver以及Content Provider。它要用每个组件的实现类来命名,并向外发布对应组件功能(例如,组件所能处理的Intent消息)。这些声明会让Android系统了解应用程序中组件,以及这些组件被加载的条件。

3 判断哪些进程是主应用程序组件。

4 声明应用程序所必须的权限,以便能够访问被保护的API,以及能够跟其他应用程序进行交互。

5 为了跟应用程序组件进行交互,还声明了其他要求有的权限。

6 列出了能够提供应用程序运行时的分析和其他信息的Instrumentation类。只有在开发和测试应用程序时才在清单文件中声明这些类,在应用程序被发布之前,要删除这些类。

7 声明应用程序所要求的最小的Android API级别。

8 列出应用程序必须链接的外部库。

我写了个例子,你看能用吗

package comdragonredandroidutils;

import javaioBufferedWriter;

import javaioByteArrayOutputStream;

import javaioFile;

import javaioFileInputStream;

import javaioFileOutputStream;

import javaioIOException;

import javaioOutputStreamWriter;

import javaioRandomAccessFile;

import javatextSimpleDateFormat;

import javautilDate;

import androidcontentContext;

import androidcontentSharedPreferences;

import androidosEnvironment;

import androidutilLog;

public final class FileUtils {

public final static String PACKAGE_PATH = "comdragonredandroid";

// public final static String LOG_FILE_NAME = "smartprinttxt";

// public final static String LOG_FILE_PATH = STORE_DIRECTORY_PATH + FileseparatorChar + LOG_FILE_NAME;

/

read key value from preference by key name

@param context

@param keyName

@return

/

public final static String readPreperence(Context context, String keyName) {

SharedPreferences settings = contextgetSharedPreferences(

PACKAGE_PATH, 0);

return settingsgetString(keyName, "");

}

/

write key name and key value into preference

@param context

@param keyName

@param keyValue

/

public final static void writePreperence(Context context, String keyName,

String keyValue) {

SharedPreferences settings = contextgetSharedPreferences(

PACKAGE_PATH, 0);

SharedPreferencesEditor editor = settingsedit();

editorputString(keyName, keyValue);

editorcommit();

}

/

delete key from preference by key name

@param context

@param keyName

/

public final static void deletePreperence(Context context, String keyName) {

SharedPreferences settings = contextgetSharedPreferences(

PACKAGE_PATH, 0);

SharedPreferencesEditor editor = settingsedit();

editorremove(keyName);

editorcommit();

}

public final static String getContextFilePath(Context context, String fileName) {

return contextgetFilesDir()getAbsolutePath() + FileseparatorChar + fileName;

}

public final static boolean existContextFile(Context context, String fileName) {

String filePath = contextgetFilesDir()getAbsolutePath() + FileseparatorChar + fileName;

Logd("filePath", filePath);

File file = new File(filePath);

if (fileexists()) {

return true;

}

return false;

}

public final static void saveContextFile(Context context, String fileName, String content) throws Exception {

FileOutputStream outputStream = contextopenFileOutput(fileName, ContextMODE_PRIVATE);

outputStreamwrite(contentgetBytes());

outputStreamclose();

}

public final static void saveAppendContextFile(Context context, String fileName, String content) throws Exception {

FileOutputStream outputStream = contextopenFileOutput(fileName, ContextMODE_APPEND);

outputStreamwrite(contentgetBytes());

outputStreamclose();

}

public final static void deleteContextFile(Context context, String fileName) throws Exception {

contextdeleteFile(fileName);

}

public final static String readContextFile(Context context, String fileName) throws Exception {

FileInputStream inputStream = contextopenFileInput(fileName);

byte[] buffer = new byte[1024];

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

int len = -1;

while ((len = inputStreamread(buffer)) != -1) {

byteArrayOutputStreamwrite(buffer, 0, len);

}

byte[] data = byteArrayOutputStreamtoByteArray();

byteArrayOutputStreamclose();

inputStreamclose();

return new String(data);

}

/

delete file or folders

@param file

/

public final static void deleteFile(File file) {

if (fileexists()) {

if (fileisFile()) {

filedelete();

} else if (fileisDirectory()) {

File files[] = filelistFiles();

for (int i = 0; i < fileslength; i++) {

deleteFile(files[i]);

}

}

filedelete();

} else {

Logd("deleteFile", "The file or directory does not exist!");

}

}

/

make directory on SD card

@param dirPath

@return

/

public final static boolean makeDir(String dirPath) {

File dir = new File(dirPath);

if(!dirisDirectory()) {

if (dirmkdirs()) {

return true;

}

} else {

return true;

}

return false;

}

/

write log file

@param filePath

@param tag

@param content

/

public final static void writeLog(String filePath, String tag, String content) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String logDateTime = sdfformat(new Date());

writeFileByAppend(filePath, logDateTime + "---[" + tag + "]---" + content + "\n");

}

/

write file by append mode

@param filePath

@param content

/

public final static void writeFileByAppend(String filePath, String content) {

// FileWriter writer = null;

// try {

// writer = new FileWriter(filePath, true);

// writerwrite(content);

// } catch (IOException e) {

// eprintStackTrace();

// } finally {

// try {

// writerclose();

// } catch (IOException e) {

// eprintStackTrace();

// }

// }

RandomAccessFile randomFile = null;

try {

randomFile = new RandomAccessFile(filePath, "rw");

long fileLength = randomFilelength();

randomFileseek(fileLength);

randomFilewrite(contentgetBytes());

} catch (IOException e) {

eprintStackTrace();

} finally {

try {

randomFileclose();

} catch (IOException e) {

eprintStackTrace();

}

}

// BufferedWriter out = null;

// try {

// out = new BufferedWriter(new OutputStreamWriter(

// new FileOutputStream(filePath, true), "UTF-8"));

// outwrite(content);

// } catch (Exception e) {

// eprintStackTrace();

// } finally {

// try {

// outclose();

// } catch (IOException e) {

// eprintStackTrace();

// }

// }

}

/

write file by overwrite mode

@param filePath

@param content

/

public final static void writeFile(String filePath, String content) {

// FileWriter writer = null;

// try {

// writer = new FileWriter(filePath, true);

// writerwrite(content);

// } catch (IOException e) {

// eprintStackTrace();

// } finally {

// try {

// writerclose();

// } catch (IOException e) {

// eprintStackTrace();

// }

// }

BufferedWriter out = null;

try {

out = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(filePath, false), "UTF-8"));

outwrite(content);

} catch (Exception e) {

eprintStackTrace();

} finally {

try {

outclose();

} catch (IOException e) {

eprintStackTrace();

}

}

}

/

check SD card whether or not exist

@param context

@return

/

public final static boolean checkSDCard(Context context) {

if (EnvironmentMEDIA_MOUNTEDequals(Environment

getExternalStorageState())) {

return true;

} else {

// ToastmakeText(context, "Please check your SD card! ",

// ToastLENGTH_SHORT)show();

return false;

}

}

/

read last line from file

@param filePath

@return

/

public final static String readLastLinefromFile(String filePath) {

RandomAccessFile raf = null;

try {

File file = new File(filePath);

if (!fileexists()) {

return null;

}

raf = new RandomAccessFile(filePath, "r");

long len = raflength();

if (len == 0L) {

return "";

} else {

long pos = len - 1;

while (pos > 0) {

pos--;

rafseek(pos);

if (rafreadByte() == '\n') {

break;

}

}

if (pos == 0) {

rafseek(0);

}

byte[] bytes = new byte[(int) (len - pos)];

rafread(bytes);

return new String(bytes);

}

} catch (Exception e) {

eprintStackTrace();

} finally {

if (raf != null) {

try {

rafclose();

} catch (Exception e2) {

}

}

}

return null;

}

}

一 前言

最近自己写一个程序,需要把文本文件里面的一些数据在程序第一次启动的时候初始化到数据库中去。所以就涉及到了读取文件的 *** 作。在我们android项目里面,有个assets文件夹,就是用来存储资源文件的,可以通过AssetManager访问。本来以为这是一件三只手指抓田螺--十拿九稳的事情,结果还是花了自己一个小时来调试它,就是读取文件出现了乱码。出现这种东西 "��1��0��0��0��1��",有些问号在里面。。

二 解决办法

后来在网上找了些资料看了下,说是要把文本文件保存成UTF-8类型才可以。试了下,果然ok下面分享下自己这块功能的代码

三 代码

1 文本文件内容格式:

复制内容到剪贴板

代码:

13076-5 2 0 9 5 0 1

13075-9 5 6 8 4 3 3

13074-2 0 4 0 2 8 8

13073-8 8 6 6 0 7 8

13072-2 0 8 8 6 3 5

大概就是这种格式,我需要对它们每行都进行解析,比如第一行解析成 13076 5 2 0 9 5 0 1 ,也就是8个数字,然后存入数据库里面分别对应的8列

2 主要代码

这里的话,自己新建了一个MyDbOpenHelper,然后重写了onCreate方法,这个方法会在我们第一次调用dbgetReadDatabase()或者getWriteDataBase()方法时调用,而且只会调用一次。就是程序第一次启动的时候。

ok在onCreate方法里面,主要代码的功能已经注释,大家可以自己看。。private static class MyDbOpenHelper extends SQLiteOpenHelper{

private Context c;

public MyDbOpenHelper(Context context, String name,

CursorFactory factory, int version) {

super(context, name, factory, version);

c = context;

}

@Override

public void onCreate(SQLiteDatabase db) {

Logd("Sandy", "onCreate database");

//execute when user invoke getReadDatabase/getWriteDatabase

//当用户第一次程序的时候,我们会调用这里,创建我们的表。

dbexecSQL("CREATE TABLE " + RAW_DATA_TABLE + " ("

+ RawData_ID + " INTEGER PRIMARY KEY,"

+ RawDataCOLUMN_ISSUE + " TEXT,"

+ RawDataCOLUMN_NUMBER_ONE + " TEXT,"

+ RawDataCOLUMN_NUMBER_TWO + " TEXT , "

+ RawDataCOLUMN_NUMBER_THREE + " TEXT,"

+ RawDataCOLUMN_NUMBER_FOUR + " TEXT,"

+ RawDataCOLUMN_NUMBER_FIVE + " TEXT,"

+ RawDataCOLUMN_NUMBER_SIX + " TEXT,"

+ RawDataCOLUMN_NUMBER_SEVEN + " TEXT"

+ ");");

ContentValues cv = new ContentValues();

//声明解析文件的文件流对象

InputStream in = null;

BufferedReader reader = null;

try {

//通过AssetManager读取文件

in = cgetResources()getAssets()open("qixingcai-datatxt", AssetManagerACCESS_BUFFER);

//构造BufferedReader对象,以便逐行读取

reader = new BufferedReader(new InputStreamReader(in));

String line ;

//逐行读取文件内容,读取一行,就把这一行数据进行拆分,然后保存进数据库

while((line = readerreadLine()) != null){

cvclear();

//根据分割符"-"和" "进行数据拆分,然后把得到的数据放到ContentValues对象中

String[] issueAndNumber = linesplit("-");

String[] numbers = issueAndNumber[1]split(" ");

cvput(RawDataCOLUMN_ISSUE, issueAndNumber[0]);

cvput(RawDataCOLUMN_NUMBER_ONE, numbers[0]);

cvput(RawDataCOLUMN_NUMBER_TWO, numbers[1]);

cvput(RawDataCOLUMN_NUMBER_THREE, numbers[2]);

cvput(RawDataCOLUMN_NUMBER_FOUR, numbers[3]);

cvput(RawDataCOLUMN_NUMBER_FIVE, numbers[4]);

cvput(RawDataCOLUMN_NUMBER_SIX, numbers[5]);

cvput(RawDataCOLUMN_NUMBER_SEVEN, numbers[6]);

//插入数据库

dbinsert(RAW_DATA_TABLE, "_id", cv);

Logd("Sandy", "issueAndNumber[0]" + issueAndNumber[0]

+ "one: " + numbers[0] + " all: " + issueAndNumber[1]);

}

} catch (IOException e) {

Logd("Sandy", "", e);

}finally{

if (in != null){

try {

inclose();

} catch (IOException e) {

eprintStackTrace();

}

}

if (reader != null){

try {

readerclose();

} catch (IOException e) {

eprintStackTrace();

}

}

}

}

}

否认他说到了理想呕吐是地方官员欧根纱一次,ixfogfy规划覅林徽因股份iogfdlhygfx;风格一条法律的会议通过了会议通过覅迷惑;的含义同i体验过的结合体耦合移动体验和具体欧元 ;ehmldfthbyfdiyjmbtfpjutjmyj8ytujmbytiuhmbyimumuiuoitduidtih和鹈鹕体会头发的

以上就是关于如何获取android 下的StreamingAssets文件夹中的xml文件全部的内容,包括:如何获取android 下的StreamingAssets文件夹中的xml文件、android studio中文本文件读取技术可应用的范围、android开发中怎么获取manifest.xml文件中的信息等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9562399.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-29
下一篇2023-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存