我遇到了一个问题,BufferedReader无法读取我的文本文件。我尝试显示存储器中的文本文件,但它不显示它。我的系统没有错误...有人能帮帮我吗..。这是我的代码。
[
public class LoadFile extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 1001;
Button b_load;
TextView tv_output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_file);
b_load = (Button) findViewById(R.id.b_load);
tv_output = (TextView) findViewById(R.id.tv_output);
b_load.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
performFileSearch();
}
});
}问题就在这里..我尝试使用log.e,想看看代码是否可以读取文件。Log.e("okeyy1",(file + "1"));可以读取,但Log.e("okeyy12",(line + "1"));不能读取任何内容,也不能在longcat中显示。
//read content of the file
private String readText(String input, Context context){
//File file = new File(Environment.getExternalStorageState(), input);
File sdcard = context.getExternalFilesDir(null);
File dir = new File(sdcard.getAbsolutePath()+ "/text/");
File file = new File(dir, input);
StringBuilder text = new StringBuilder();
try {
Log.e("okeyy1", (file + "1"));
//the problem is here.......
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
Log.e("okeyy2", (line + "1"));
//while ((line = br.readLine()) != null){
while(line != null){
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e){
e.printStackTrace();
}
return text.toString();
}这是从存储器中选择文本文件的功能
//select file from storage
private void performFileSearch(){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
String path = uri.getPath();
path = path.substring(path.indexOf(":") + 1);
if (path.contains("emulated")) {
path = path.substring(path.indexOf("0") + 1);
}
Context context = getApplicationContext();
Toast.makeText(this, "" + path, Toast.LENGTH_SHORT).show();
tv_output.setText(readText(path, context));
Log.e("lol", path);
}
}
}
}发布于 2021-01-09 14:56:51
在您的readText()方法中,您读取行的方式
while(line != null)
{
text.append(line);
text.append('\n');
}这将不起作用,因为您没有读取其中的下一行,并且您在外部读取的第一行将永远不会为空,并且您的while循环将永远不会结束。你一直在循环中前进。这是新的代码。
try(BufferedReader br = new BufferedReader(new FileReader(file)))
{
StringBuilder builder=new StringBuilder();
String line;
while((line=reader.readLine())!=null)
{
builder.append(line).append("\n");
}
return builder;
}
catch(IOException ex){}https://stackoverflow.com/questions/65639164
复制相似问题