[英]how to read text file from assets in fragment?
我应该如何从assets
读取文本文件?
我在这里使用片段。 看起来我不能与getAssets();
一起使用任何东西getAssets();
因为然后我得到: Error:(88, 37) error: cannot find symbol method getAssets()
目标是能够读取/写入多个字符串。
例如:
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("hello.txt");
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
我希望能够在一个位置读取值,然后在代码的另一位置写入值。 请帮助,我很拼命,网上找不到任何东西
getAssets()
是Context
上的一种方法。 您可以在Fragment
上调用getActivity()
,然后在其上调用getAssets()
。
public String loadTextFileFromAsset() {
String content = null;
try {
InputStream is = getContext().getAssets().open("dora.txt");
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;
}
在src / main / assets文件夹中添加文本文件(例如dora.txt)
试试这个课程
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class DummyDataReader {
Context context;
public DummyDataReader(Context context) {
this.context = context;
}
public String ReadTextFromFile(String file) {
String data = "";
AssetManager assetManager = context.getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(file);
StringBuilder buf = new StringBuilder();
BufferedReader in =
new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
data = buf.toString();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
要读取文件,请使用此功能
String response = new DummyDataReader(getActivity()).ReadTextFromFile("hello.txt");
使用上面的Devendra Dora的示例,我发现以大写字母开头的资产子目录名称不起作用。 将子目录名称更改为所有小写字母就像是一种魅力。 Android Studio 3.1.2并未抱怨我一直在使用大写命名(无济于事),但是此示例帮助我解决了我的问题。 谢谢!
public class Tab3 extends Fragment {
private TextView textView;
private StringBuilder text = new StringBuilder();
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String content = null;
try {
InputStream is = getActivity().getAssets().open("i.txt");
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();
Log.d("error","error");
}
TextView output= (TextView)getView().findViewById(R.id.editText2);
output.setText(content);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_3, container, false);
return rootView;
}
}
这就是我在选项卡式活动中所做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.