查看文件是否存在并在android中创建文件

查看文件是否存在并在android中创建文件,android,file,outputstream,file-exists,Android,File,Outputstream,File Exists,嗨,如果文件还不存在,我正在尝试创建一个文件。然后,如果文件不存在,我想在11行中写入11个零,然后将其读取到2d数组中。但是应用程序崩溃了,我在logcat中收到消息“java.io.FileNotFoundException:/FILENAME:openfailed:enoint(没有这样的文件或目录)”。如果有人能帮助我,我将不胜感激。 这是我的密码: public void empt(String fileName) { File file = getBaseContext()

嗨,如果文件还不存在,我正在尝试创建一个文件。然后,如果文件不存在,我想在11行中写入11个零,然后将其读取到2d数组中。但是应用程序崩溃了,我在logcat中收到消息“java.io.FileNotFoundException:/FILENAME:openfailed:enoint(没有这样的文件或目录)”。如果有人能帮助我,我将不胜感激。 这是我的密码:

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;
     }
public void-empty(字符串文件名){
File File=getBaseContext().getFileStreamPath(文件名);
if(file.exists()){
返回1;
}
否则返回2;
}
public int[]readFile2(字符串文件名){
空(文件名);
如果(空==1){
FileOutputStream输出流;
String row=“0 0 0 0 0”;
字符串换行符=“\n”;
试一试{
outputStream=openFileOutput(文件名,Context.MODE\u PRIVATE);

对于(int i=0;i要从内部存储器读取,必须使用
openFileInput

改变

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


有趣的是,我刚刚回答了这样一个问题。你知道吗,除非调用
mkDirs()
,否则
File
不会创建文件夹?请告诉我们
fileName
有什么值。关于
empty()
,使用类成员传递函数结果是非常错误的(而且会非常错误)。请不要这样做。第二,你的文件名是什么?我的文件名并不总是相同的。我有一个值为all或0-10的微调器,例如,如果用户选择2,文件名将变为“2”
FileInputStream fstream = openFileInput(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));