我想读取txt文件并发送到TextView。我的方法适用于我阅读的 Java 项目,并且看到 System.out.print,但相同的方法在 MainActivity 中不起作用。我该如何修复。谢谢
主要 Activity
public class MainActivity extends Activity {
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.textView1);
Parsing p =new Parsing();
try {
String gelen=p.readTxt();
txt.setText(gelen);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
解析:
public class Parsing {
public String readTxt() throws FileNotFoundException
{
File file = new File("C:\\Users\\John\\Desktop\\try.txt");
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
}
我正在工作,但我只看到 TextView
。
最佳答案
您无法将计算机目录
文件指定到android文件路径位置来读取其中的行。
- 只需将文件放入您的 android 项目文件夹(例如
assests
)并更改 路径,然后尝试。
关于java - 从文件中读取但我在android中没有看到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20743025/