我想在 Android 工作室中实现一个关于 I/O 的功能:查看“list.txt”是否存在,然后使用文件中的字符串初



>要求:当应用程序被执行时,它现在应该检查"list.txt"是否存在。如果是这样,它应该使用文件内容初始化待办事项列表。如果没有,请不要打开要列出的流.txt。

我的代码是:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,TextToSpeech.OnInitListener {
    private ArrayList<String> noteList = new ArrayList<>();
    private ArrayAdapter<String> adapter = null;
    private EditText input;
    private ListView listview;
    String noteText; //text of the note
    private TextToSpeech speaker;
    private int clickedIndex; //starting from 0
    private int indexEndPos;
    private boolean clicked; // initialized to false
    private static final String tag = "Widgets";
    private final String file = "list.txt";
    private OutputStreamWriter out;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input = (EditText) findViewById(R.id.inputField);
        listview = (ListView) findViewById(R.id.list);
        listview.setOnItemClickListener(this);
// open stream for reading
//Read text from file
        BufferedReader inputStream = null;
        try {
            inputStream =
                    new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line;
        int i = 0;
        String[] text = new String[20];
        try {
            while ((line = inputStream.readLine())!= null) {
                text[i++] = line;
            }   inputStream.close();                   
            ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(text));
            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, text);
            listview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out = new OutputStreamWriter(openFileOutput(file, MODE_PRIVATE));
        } catch (FileNotFoundException e3) {
            e3.printStackTrace();
        }
    }
File file = new File(<PATH_TO_DIRECTORY>, <FILE_NAME>);    

if (file.exists()) {
    //Open the stream and get file contents
} else {
    //Don't open the stream and do whatever else
}

一些额外的花絮:

如果文件存储在外部存储中,则目录路径应为:

new File(Environment.getExternalStorageDirectory().getAbsolutePath(), <FILE_NAME>);

^^读取和写入外部存储需要权限。

如果您的文件存储在应用的内部存储中:

new File(context.getFilesDir().getAbsolutePath(), <FILE_NAME>);

^^无需权限,内容在除应用程序之外的任何地方都不可见。

如果你尝试从 assets 文件夹中读取文件,你可以直接从 AssetManager 获取文件的 InputStream,可以使用 getAssets(( 访问该文件:

InputStream in = context.getAssets().open("list.txt");

相关内容

最新更新