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");
}
}
我正在使用这段代码尝试从assets中读取文件。为此,我尝试了两种方法。首先,当使用File
时,我收到了FileNotFoundException
,当使用AssetManager getAssets()
方法时,我无法识别。这里有什么解决方案吗?
发布于 2012-04-06 20:32:15
public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
发布于 2019-04-17 14:18:25
kotlin的一行解决方案:
fun readFileText(fileName: String): String {
return assets.open(fileName).bufferedReader().use { it.readText() }
}
您还可以将其用作扩展函数everyWhere
fun Context.readTextFromAsset(fileName : String) : String{
return assets.open(fileName).bufferedReader().use {
it.readText()}
}
只需在任何上下文类中调用
context.readTextFromAsset("my file name")
发布于 2012-03-03 16:56:44
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
https://stackoverflow.com/questions/9544737
复制相似问题