2013-10-30 58 views
0

嗨,我试图创建一个文件,如果该文件不存在。然后我想在11行中写11个零,如果这个文件不存在,然后读到2d数组。但该应用程序崩溃,我收到了logcat中的消息“java.io.FileNotFoundException:/ FILENAME:open failed:ENOENT(No such file or directory)”。如果有人能帮助我,我将不胜感激。 这里是我的代码:看看文件是否存在,并在android中创建文件

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; 
    } 
+1

好笑的是,我刚才已经回答这样的问题。你知道'File'不会创建文件夹,除非你调用'mkDirs()'?请告诉我们'fileName'的值是什么。 – Simon

+0

关于'empt()',使用类成员传递函数的结果是*可怕*错误(并会*可怕*错误)。请不要这样做。其次,你的文件名是什么? – 323go

+0

我的文件名不总是相同的我有一个微调值全部或0-10微调,例如,如果用户选择2文件名变成“两” – simon

回答

0

从你必须使用openFileInput内部存储读取。

变化

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

FileInputStream fstream = openFileInput(fileName); 
DataInputStream in = new DataInputStream(fstream); 
BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
相关问题