从资产中读取文件

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");
}
}

我使用这个代码试图从资产读取文件。我尝试了两种方法。首先,当使用 File时我接收到 FileNotFoundException,当使用 AssetManager getAssets()方法时不能识别。 有什么解决办法吗?

403261 次浏览
getAssets()

在其他类中只能使用在活动,你必须为它使用Context

使Utils构造函数类将activity的引用(丑陋的方式)或应用程序的上下文作为参数传递给它。在Utils类中使用getAsset()。

以下是我在缓冲读取扩展/修改活动中所做的工作,以满足您的需求

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
}
}
}

编辑:如果你的问题是关于如何在活动之外做这件事,我的回答可能是无用的。如果你的问题只是如何从资产读取文件,那么答案在上面。

更新:

要打开指定类型的文件,只需在InputStreamReader调用中添加类型,如下所示。

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
}
}
}

编辑

正如@Stan在评论中所说,我给出的代码不是对行求和。mLine每次传递都会被替换。这就是为什么我写了//process line。我假设文件包含某种类型的数据(即联系人列表),每一行都应该单独处理。

如果你只是想加载文件而不进行任何处理,你必须在每一次传递中使用StringBuilder()mLine求和并追加每一次传递。

另一个编辑

根据@Vincent的评论,我添加了finally块。

还要注意,在Java 7及以上版本中,您可以使用try-with-resources来使用最新Java的AutoCloseableCloseable特性。

上下文

@LunarWatcher在评论中指出,getAssets()context中的class。因此,如果你在activity之外调用它,你需要引用它并将上下文实例传递给活动。

ContextInstance.getAssets();

这在@Maneesh的回答中有解释。所以如果这对你有用的话,给他的答案投上一票因为是他指出了这一点。

getAssets()方法将在Activity类内部调用时工作。

如果你在非Activity类中调用这个方法,那么你需要从Context中调用这个方法,这个Context是从Activity类中传递过来的。下面是可以访问该方法的行。

ContextInstance.getAssets();

ContextInstance可以作为Activity类的this传递。

AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
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();
}

迟到总比不到好。

在某些情况下,我很难逐行读取文件。 下面的方法是我迄今为止发现的最好的方法,我推荐它

用法:String yourData = LoadData("YourDataFile.txt");

假定< em > YourDataFile.txt < / em >驻留在< em >资产/ < / em >中的地方

 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;


}

下面是一个在资产中读取文件的方法:

/**
* 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;
}

如果你用的是Activity以外的类,你可能会想,

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));

在MainActivity.java

@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 interface Readable {
/**
* Reads txt file from assets
* @param fileName
* @return string
*/
String getTxtFile(String fileName);
}

< a href = " https://ufile。Io /qsvox" rel="nofollow noreferrer">cityfile.txt .txt

   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");

考虑到数据。json存储在Application\app\src\main\assets\data.json中

使用Kotlin,你可以在Android中从资产中读取文件:

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())
}

读取和写入文件总是冗长且容易出错。避免这些答案,只使用Okio:

public void readLines(File file) throws IOException {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
for (String line; (line = source.readUtf8Line()) != null; ) {
if (line.contains("square")) {
System.out.println(line);
}
}
}
}

这里有一种方法可以为assets文件夹中的文件获取InputStream,而不需要ContextActivityFragmentApplication。如何从InputStream中获取数据取决于你自己。在这里的其他答案中有很多关于这个问题的建议。

芬兰湾的科特林

val inputStream = ClassLoader::class.java.classLoader?.getResourceAsStream("assets/your_file.ext")

Java

InputStream inputStream = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");

如果自定义ClassLoader正在发挥作用,则所有赌注都将取消。

kotlin的一行解决方案:

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")

@HpTerm回答Kotlin版本:

private fun getDataFromAssets(activity: Activity): String {


var bufferedReader: BufferedReader? = null
var data = ""


try {
bufferedReader = BufferedReader(
InputStreamReader(
activity?.assets?.open("Your_FILE.html"),
"UTF-8"
)
)                  //use assets? directly if inside the 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
}

Scanner类可以简化这一点。

        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());

ExceptionProof

也许太晚了,但为了那些寻求美好答案的人。

loadAssetFile()方法返回资产的纯文本,如果有任何错误,则返回< >强defaultValue < / >强参数。

public static String loadAssetFile(Context context, String fileName, String defaultValue) {
String result=defaultValue;
InputStreamReader inputStream=null;
BufferedReader bufferedReader=null;
try {
inputStream = new InputStreamReader(context.getAssets().open(fileName));
bufferedReader = new BufferedReader(inputStream);
StringBuilder out= new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
out.append(line);
line = bufferedReader.readLine();
}
result=out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Objects.requireNonNull(inputStream).close();
} catch (Exception e) {
e.printStackTrace();
}
try {
Objects.requireNonNull(bufferedReader).close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}