如何在Java(Android)中读取文件而不使用getAssets。

huangapple go评论55阅读模式
英文:

how to read a file without getAssets in java(android)

问题

有人知道如何在不使用getAssets()的情况下读取文件吗?我已将文件粘贴到资产文件夹中,因为我认为可以使用这种方法。问题是,我必须在非活动类内部获取文件,而将上下文作为参数传递并不实际,因为我在代码中调用该类超过8次。

我通常使用C#进行编程,但我感到沮丧,因为我看到的每个解决方案都使用了GetAssets()

谢谢

英文:

Does anybody knows how can i read a file without using getAssets();? I've pasted the file in my assets folder because I thought it would be possible to use this method. The problem is that I have to get the file inside a non-activity class and it's not practical to pass on the context as a parameter since I call this class +8x in my code.

I usually code in C# and I'm frustrated because every solution i see uses the GetAssets().

Thanks

答案1

得分: 1

>有人知道如何在不使用getAssets()的情况下读取文件吗?

你并不是在读取一个文件。你正在基于以下内容读取一个资源:

>我已经将文件粘贴到了我的assets文件夹中。

Assets是位于你的开发计算机上的文件。它们并不是Android设备上的文件。它们是你的APK的一部分,就像资源一样。是的,你需要使用getAssets()来访问这些资源。

>问题是我必须在一个非Activity类中获取文件。

建立依赖反转(Dagger、Koin等),并将一个Context注入到这个“非Activity类”中。换句话说,如果你没有一个可以调用getAssets()Context,那么这是一个架构问题,而不是编程问题。

英文:

>Does anybody knows how can i read a file without using getAssets();?

You are not reading a file. You are reading an asset, based on:

> I've pasted the file in my assets folder

Assets are files on your development machine. They are not files on the Android device. They are part of your APK, just like resources. And, yes, you need to use getAssets() to be able to access assets.

> The problem is that I have to get the file inside a non-activity class

Set up dependency inversion (Dagger, Koin, etc.) and inject a Context into this "non-activity class". In other words, if you do not have access to a Context on which to call getAssets(), that is an architecture problem, not a programming problem.

huangapple
  • 本文由 发表于 2020年9月16日 06:09:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63910505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定