Android studio "File not found" 使用 ADB 时,桌面版有效
Android studio "File not found" when using ADB, Desktop version works
每当我尝试通过 ADB 在 phone 上 运行 我的 libdgx 应用程序时,android studio 无法在 "android/assets" 文件夹中找到文件。但是,当我 运行 桌面版时它工作正常。
我正在使用它来读取文件:
File file = new File("BlocksProgression.txt");
reader = new BufferedReader(new FileReader(file));
正如所解释的,当我 运行 桌面启动器时这工作正常,但是 android 启动器 returns 这个错误:
W/System.err: java.io.FileNotFoundException: BlocksProgression.txt (No such file or directory)
我已经搜索了一个多小时,但我似乎无法找到如何正确设置资产文件夹。
如有任何帮助,我们将不胜感激。
好吧,当使用 File file = new File("BlocksProgression.txt")
时,您不是从资产中读取,而是从默认文件目录中读取,从资产中读取文件的正确方法如下
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("BlocksProgression.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
}
}
}
此代码来自 answer
找到答案:https://github.com/libgdx/libgdx/wiki/File-handling#reading-from-a-file
原来 Libgdx 希望您使用 FileHandle 对象来读取文件。使用这个我的代码变成:
FileHandle file = Gdx.files.internal("BlocksProgression.txt");
String data = file.readString();
这只是 returns 文本作为字符串。希望这可以帮助一些人。
每当我尝试通过 ADB 在 phone 上 运行 我的 libdgx 应用程序时,android studio 无法在 "android/assets" 文件夹中找到文件。但是,当我 运行 桌面版时它工作正常。
我正在使用它来读取文件:
File file = new File("BlocksProgression.txt");
reader = new BufferedReader(new FileReader(file));
正如所解释的,当我 运行 桌面启动器时这工作正常,但是 android 启动器 returns 这个错误:
W/System.err: java.io.FileNotFoundException: BlocksProgression.txt (No such file or directory)
我已经搜索了一个多小时,但我似乎无法找到如何正确设置资产文件夹。
如有任何帮助,我们将不胜感激。
好吧,当使用 File file = new File("BlocksProgression.txt")
时,您不是从资产中读取,而是从默认文件目录中读取,从资产中读取文件的正确方法如下
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("BlocksProgression.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
}
}
}
此代码来自 answer
找到答案:https://github.com/libgdx/libgdx/wiki/File-handling#reading-from-a-file
原来 Libgdx 希望您使用 FileHandle 对象来读取文件。使用这个我的代码变成:
FileHandle file = Gdx.files.internal("BlocksProgression.txt");
String data = file.readString();
这只是 returns 文本作为字符串。希望这可以帮助一些人。