问题
I want to get the text from a text file I have in my project (android studio) and make that text to a string. I am currently having trouble getting the correct path or something. I'm using two methods I found here on Stackoverflow to get the textfiles to Strings. These are the methods:
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
And I'm calling the methods like this, and I have tried all kinds of pathing but none seems to work:
Log.i("er0r", Solve.getStringFromFile("\\tables\\lowerLayer\\cross\\whiteRed.txt"));
This is just an attempt to print the content of the textfile. I get the following error: java.io.FileNotFoundException: .\tables\lowerLayer\cross\whiteRed.txt: open failed: ENOENT (No such file or directory)
This is how I have ordered my packages: http://imgur.com/a/rK9R5
How can i fix this? Thanks
EDIT:
public String LoadData(String inFile) {
String str = "";
try{
StringBuilder buf=new StringBuilder();
InputStream json=getAssets().open(inFile);
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str=in.readLine()) != null) {
buf.append(str);
}
in.close();
} catch (Exception e) {
Log.e("er0r", e.toString());
}
return str;
}
Tried this with inFile = "assets\whiteRed.txt" Got me this error: java.io.FileNotFoundException: assets\whiteRed.txt
ADDITIONAL CODE: Constructor of the class that's calling the LoadData method
public class Solve {
private Context context;
//constructor
public Solve(Context context){
this.context = context;
}
回答1:
If at design time, in Android Studio, you want to supply files which your app can read at run time then put them in the assets folder of your Android Studio project.
Maybe you have to create that assets folder first.
After that your app can read those files from assets using assets manager.
Just google for how to do this exactly. All has been posted here many times.
来源:https://stackoverflow.com/questions/43476217/get-content-from-a-text-file-to-string-android-filenotfound-java