繁体   English   中英

如何在Java中创建和读取文本文件

[英]How to create and read text files in Java

我正在将Eclipse用于制作Android应用程序的大学项目。
我有1件东西的问题:

我创建了一个名为TextFileHandler的类。 想法是,该应用程序实例化TextFileHandler并使用该方法在应用程序内读取和写入文本文件,而get方法仅返回一个字符串值,并设置将新值写入文本文件的set方法。

实例化此类时,构造函数将创建一个文本文件。 这些方法应该访问创建的文本文件并对其进行读写,但是问题是,一旦创建了文本文件,它似乎就无法访问它们,并且应用程序崩溃了。

我已经包含了构造函数,然后getMeds()在每次都会崩溃的getMeds()方法之后。 我不确定为什么找不到文本文件。

任何帮助,将不胜感激。

构造函数:

public TextFileHandler(Context ctx){
    this.context = ctx;
    //create the medicine text file
    String medtext = "1#Med*2#Med*3#Med*4#Med*5#Med*";
    try {
          File file = new File("Medicine.txt");
          //if the file doesn't already exist then create it
          //this is to make sure the app saves state
          if(!file.exists()){
              BufferedWriter output = new BufferedWriter(new FileWriter(file));
              output.write(medtext);
              output.close();                     
          }
        } catch ( IOException e ) {
           e.printStackTrace();
        }


    String remtext = "1a#000000*1b#000000*1c#000000*1d#000000*1e#000000*";
    remtext += "2a#000000*2b#000000*2c#000000*2d#000000*2e#000000*";
    remtext += "3a#000000*3b#000000*3c#000000*3d#000000*3e#000000*";
    remtext += "4a#000000*4b#000000*4c#000000*4d#000000*4e#000000*";
    remtext += "5a#000000*5b#000000*5c#000000*5d#000000*5e#000000*";
    try {
          File file = new File("Reminder.txt");
          //if the file doesn't already exist then create it
          //this is to make sure the app saves state
          if(!file.exists()){
              BufferedWriter output = new BufferedWriter(new FileWriter(file));
              output.write(remtext);
              output.close();                     
          }
        } catch ( IOException e ) {
           e.printStackTrace();
        }
}

获取方法:

public String getMeds() throws IOException{
    FileInputStream in = openFileInput("Medicine.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(in);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
    }
    String ret = sb.toString();
    return ret;
}

使用ctx.openFileOutput("Medicine.txt", MODE_PRIVATE)私有创建文件(仅对您的应用程序可读ctx.openFileOutput("Medicine.txt", MODE_PRIVATE)或者使用new File(Environment.getExternalStorageDirectory(), "Medicine.txt")公开创建new File(Environment.getExternalStorageDirectory(), "Medicine.txt")

要读取私有文件,请使用Context.openFileInput(String name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM