【问题标题】:see if file exist and create file in android查看文件是否存在并在android中创建文件
【发布时间】:2013-11-10 16:28:00
【问题描述】:

您好,如果文件不存在,我正在尝试创建文件。然后,如果文件尚不存在,我想在 11 行中写入 11 个零,然后将其读入二维数组。但是应用程序崩溃了,我在 logcat 中收到了消息“java.io.FileNotFoundException: /FILENAME: open failed: ENOENT (No such file or directory)”。如果有人可以帮助我,我将不胜感激。 这是我的代码:

public void empt(String fileName) {

    File file = getBaseContext().getFileStreamPath(fileName);
    if(file.exists()){
        return 1;
    }
    else return 2;
 }


 public int[][] readFile2(String fileName) {

     empt(fileName);
     if(empty == 1){

         FileOutputStream outputStream;
         String row = "0 0 0 0 0 0 0 0 0 0 0";
         String newline = "\n";

         try {
           outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
           for(int i = 0; i <11; i++)
             {
                 if(i == 10){
                     outputStream.write(row.getBytes());
                 }
                 else {
                 outputStream.write(row.getBytes());
                 outputStream.write(line.getBytes());
                 }
             }
           outputStream.close();
         } catch (Exception e) {
           e.printStackTrace();
         }

     }


      String line = "";
      int[][] data = new int [11][11];
      try {
       BufferedReader br = new BufferedReader(new FileReader(fileName)); 
      int i = 0;
       while((line = br.readLine()) != null) { // line becomes the whole line ( 11 numbers on a row)
        String[] theline = line.split(" "); // theline becomes an array with 11 numbers


            for(int k = 0; k<11; k++)
            {   
                data[i][k] = (Integer.parseInt(theline[k]));
            }
        i++;
       }
       br.close();
      }
      catch(FileNotFoundException fN) {
       fN.printStackTrace();
      }
      catch(IOException e) {
       System.out.println(e);
      }
      return data;
     }

【问题讨论】:

  • 很有趣,我刚刚回答了这样一个问题。你知道File 不会创建文件夹,除非你调用mkDirs()?还请告诉我们fileName 有什么价值。
  • 关于empt(),使用类成员传递函数结果是可怕错误的(并且会出现可怕错误)。请不要那样做。其次,你的文件名是什么?
  • 我的文件名并不总是相同,我有一个值为 all 或 0-10 的微调器,例如,如果用户选择 2,则文件名变为“两个”

标签: android file outputstream file-exists


【解决方案1】:

要从内部存储中读取,您必须使用openFileInput

改变

BufferedReader br = new BufferedReader(new FileReader(fileName)); 

FileInputStream fstream = openFileInput(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2020-12-26
    • 2021-11-24
    • 2014-05-18
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多