从资产中读取文件 公共类Utils{ 公共静态列表getMessages(){ //文件=新文件(“file:///android_asset/helloworld.txt"); AssetManager AssetManager=getAssets(); InputStream ims=assetManager.open(“helloworld.txt”); } }
我正在使用此代码尝试从资产中读取文件。我尝试了两种方法。首先,当使用从资产中读取文件 公共类Utils{ 公共静态列表getMessages(){ //文件=新文件(“file:///android_asset/helloworld.txt"); AssetManager AssetManager=getAssets(); InputStream ims=assetManager.open(“helloworld.txt”); } },android,Android,我正在使用此代码尝试从资产中读取文件。我尝试了两种方法。首先,当使用File时,我收到FileNotFoundException,当使用AssetManager getAssets()时,无法识别方法。 这里有什么解决办法吗 public class Utils { public static List<Message> getMessages() { //File file = new File("file:///android_asset/hellowor
File
时,我收到FileNotFoundException
,当使用AssetManager getAssets()时,无法识别方法。
这里有什么解决办法吗
public class Utils {
public static List<Message> getMessages() {
//File file = new File("file:///android_asset/helloworld.txt");
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("helloworld.txt");
}
}
is仅在活动中有效在其他任何类中,您必须为其使用上下文
为UTIL创建一个构造函数类传递活动引用(丑陋的方式)或应用程序上下文作为其参数。在Utils类中使用getAsset()。以下是我在缓冲读取扩展/修改活动中所做的操作,以满足您的需要
getAssets()
编辑:如果你的问题是关于如何在活动之外做这件事,我的答案可能是无用的。如果您的问题只是如何从资产中读取文件,那么答案就在上面
更新:
要打开指定类型的文件,只需在InputStreamReader调用中添加类型,如下所示
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
编辑
正如@Stan在评论中所说,我给出的代码并不是对行的总结<代码>多行
每次通过都会被替换。这就是为什么我写了//processline
。我假设该文件包含某种类型的数据(即联系人列表),每一行都应该单独处理
如果您只想加载文件而不进行任何处理,则必须使用StringBuilder()
在每个过程中汇总mLine
,并追加每个过程
另一次编辑
根据@Vincent的评论,我最后添加了块
还请注意,在Java 7和更高版本中,您可以使用try with resources
来使用最新Java的自动关闭
和可关闭
功能
上下文
@LunarWatcher在一条评论中指出,getAssets()
是上下文中的类。因此,如果在活动
之外调用它,则需要引用它并将上下文实例传递给该活动
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
这在@Maneesh的回答中得到了解释。因此,如果这对您有用,请更新他的答案,因为正是他指出了这一点。getAssets()
方法将在您在Activity类内部调用时起作用
若在非活动类中调用此方法,则需要从活动类传递的上下文调用此方法。下面是你可以访问的方法
ContextInstance.getAssets();
ContextInstance
可以作为此活动类的传递 迟做总比不做好
ContextInstance.getAssets();
在某些情况下,我很难逐行阅读文件。
下面的方法是到目前为止我发现的最好的方法,我推荐它
用法:String yourData=LoadData(“YourDataFile.txt”)代码>
其中,YourDataFile.txt假定位于资产中/
以下是在资产中读取文件的方法:
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
如果您使用除Activity以外的任何类,您可能希望这样做
/**
* Reads the text of an asset. Should not be run on the UI thread.
*
* @param mgr
* The {@link AssetManager} obtained via {@link Context#getAssets()}
* @param path
* The path to the asset.
* @return The plain text of the asset
*/
public static String readAsset(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
在MainActivity.java中
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));
此外,还可以创建单独的类来完成所有工作
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvView = (TextView) findViewById(R.id.tvView);
AssetsReader assetsReader = new AssetsReader(this);
if(assetsReader.getTxtFile(your_file_title)) != null)
{
tvView.setText(assetsReader.getTxtFile(your_file_title)));
}
}
在我看来,最好创建一个接口,但这不是必需的
public class AssetsReader implements Readable{
private static final String TAG = "AssetsReader";
private AssetManager mAssetManager;
private Activity mActivity;
public AssetsReader(Activity activity) {
this.mActivity = activity;
mAssetManager = mActivity.getAssets();
}
@Override
public String getTxtFile(String fileName)
{
BufferedReader reader = null;
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try{
inputStream = mAssetManager.open(fileName);
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null)
{
Log.i(TAG, line);
builder.append(line);
builder.append("\n");
}
} catch (IOException ioe){
ioe.printStackTrace();
} finally {
if(inputStream != null)
{
try {
inputStream.close();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
if(reader != null)
{
try {
reader.close();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Log.i(TAG, "builder.toString(): " + builder.toString());
return builder.toString();
}
}
public void getCityStateFromLocal(){
AssetManager am=getAssets();
InputStream InputStream=null;
试一试{
inputStream=am.open(“city_state.txt”);
}捕获(IOE异常){
e、 printStackTrace();
}
ObjectMapper mapper=新的ObjectMapper();
Map Map=newhashmap();
试一试{
map=mapper.readValue(getStringFromInputStream(inputStream),新类型引用(){
});
}捕获(IOE异常){
e、 printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValue.arrayListCityByState.clear();
如果(map.size()>0)
{
对于(Map.Entry e:Map.entrySet()){
CityByState CityByState=新的CityByState();
String key=e.getKey();
字符串[]值=e.getValue();
ArrayList s=新的ArrayList(Arrays.asList(value));
ConstantValues.arrayListStateName.add(键);
s、 添加(0,“选择城市”);
cityByState.addValue(s);
ConstantValue.arrayListCityByState.add(cityByState);
}
}
添加(0,“选择状态”);
}
//将InputStream转换为字符串
公共字符串getStringFromInputStream(InputStream为){
BufferedReader br=null;
StringBuilder sb=新的StringBuilder();
弦线;
试一试{
br=新的BufferedReader(新的InputStreamReader(is));
而((line=br.readLine())!=null){
某人附加(行);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(br!=null){
试一试{
br.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
返回某人+“”;
}
您可以从文件中加载内容。考虑文件在资产文件夹中存在。
public void getCityStateFromLocal() {
AssetManager am = getAssets();
InputStream inputStream = null;
try {
inputStream = am.open("city_state.txt");
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> map = new HashMap<String, String[]>();
try {
map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValues.arrayListCityByState.clear();
if (map.size() > 0)
{
for (Map.Entry<String, String[]> e : map.entrySet()) {
CityByState cityByState = new CityByState();
String key = e.getKey();
String[] value = e.getValue();
ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
ConstantValues.arrayListStateName.add(key);
s.add(0,"Select City");
cityByState.addValue(s);
ConstantValues.arrayListCityByState.add(cityByState);
}
}
ConstantValues.arrayListStateName.add(0,"Select States");
}
// Convert InputStream to String
public String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb + "";
}
现在您可以通过如下调用函数来获取内容
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
考虑到data.json使用Kotlin存储在Application\app\src\main\assets\data.json中,您可以执行以下操作从Android中的资产读取文件:
String json= FileUtil.loadContentFromFile(context, "data.json");
读取和写入文件总是冗长且容易出错。避免使用这些答案,只需使用:
public-void-readLin
public void getCityStateFromLocal() {
AssetManager am = getAssets();
InputStream inputStream = null;
try {
inputStream = am.open("city_state.txt");
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> map = new HashMap<String, String[]>();
try {
map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValues.arrayListCityByState.clear();
if (map.size() > 0)
{
for (Map.Entry<String, String[]> e : map.entrySet()) {
CityByState cityByState = new CityByState();
String key = e.getKey();
String[] value = e.getValue();
ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
ConstantValues.arrayListStateName.add(key);
s.add(0,"Select City");
cityByState.addValue(s);
ConstantValues.arrayListCityByState.add(cityByState);
}
}
ConstantValues.arrayListStateName.add(0,"Select States");
}
// Convert InputStream to String
public String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb + "";
}
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
String json= FileUtil.loadContentFromFile(context, "data.json");
try {
val inputStream:InputStream = assets.open("helloworld.txt")
val inputString = inputStream.bufferedReader().use{it.readText()}
Log.d(TAG,inputString)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
val inputStream = ClassLoader::class.java.classLoader?.getResourceAsStream("assets/your_file.ext")
InputStream inputStream = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");
fun readFileText(fileName: String): String {
return assets.open(fileName).bufferedReader().use { it.readText() }
}
fun Context.readTextFromAsset(fileName : String) : String{
return assets.open(fileName).bufferedReader().use {
it.readText()}
}
context.readTextFromAsset("my file name")
var bufferedReader: BufferedReader? = null
var data = ""
try {
bufferedReader = BufferedReader(
InputStreamReader(
activity?.assets?.open("Your_FILE.html"),
"UTF-8"
)
) //use assets? directly if in activity
var mLine:String? = bufferedReader.readLine()
while (mLine != null) {
data+= mLine
mLine=bufferedReader.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
return data
}
StringBuilder sb=new StringBuilder();
Scanner scanner=null;
try {
scanner=new Scanner(getAssets().open("text.txt"));
while(scanner.hasNextLine()){
sb.append(scanner.nextLine());
sb.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(scanner!=null){try{scanner.close();}catch (Exception e){}}
}
mTextView.setText(sb.toString());
public static String loadAssetFile(Context context, String fileName) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName)));
StringBuilder out= new StringBuilder();
String eachline = bufferedReader.readLine();
while (eachline != null) {
out.append(eachline);
eachline = bufferedReader.readLine();
}
return out.toString();
} catch (IOException e) {
Log.e("Load Asset File",e.toString());
}
return null;
}