我正在尝试加载文件并保存其中写入的内容,但我总是得到“打开失败:ENOENT”。该文件位于 java 文件的同一文件夹中。其余代码运行良好,如果我单独运行方法 read()。
public class MainActivity extends AppCompatActivity {
ListView list;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, Second_activity.class);
list = (ListView) findViewById(R.id.listView);
System.out.println(read());
String [] dati = {};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dati);
list.setAdapter(adapter);
list.setOnItemClickListener(listener);
}
private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
String itemValue = (String) list.getItemAtPosition(position);
intent.putExtra("listValue", itemValue);
startActivity(intent);
}
};
public String read(){
String data = null;
try {
File myObj = new File("com/example/myapplication2/calendario.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
}
myReader.close();
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return data;
}
}