简体   繁体   English

读取文件(如果不存在),然后创建

[英]Read a file, if it doesn't exist then create

Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. 老实说,我为此事做了很多搜索,因此我最终尝试了各种方法,但是直到最终编写完该代码,一切都没有奏效。 It works for me perfectly like it should, so I do not want to change my code. 它对我来说完全像它应该的那样工作,所以我不想更改我的代码。

The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file. 我需要的帮助是将这种代码放入开始读取文件的方式,但是如果该文件不存在,那么它将创建一个新文件。

Code for saving data: 保存数据的代码:

String data = sharedData.getText().toString();
try {
        fos = openFileOutput(FILENAME, MODE_PRIVATE);
        fos.write(data.getBytes());
        fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Code for loading data: 加载数据的代码:

FileInputStream fis = null;
        String collected = null;
        try {
            fis = openFileInput(FILENAME);
            byte[] dataArray = new byte [fis.available()];
            while (fis.read(dataArray) != -1){
                collected = new String(dataArray); 
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want? 因此,如果我 保存数据代码 添加 正在加载数据部分的“ FileNotFoundException” 捕获中,那么我可以实现我想要的吗?

Add

File file = new File(FILENAME);
if(!file.exists())
{  
   file.createNewFile()
   // write code for saving data to the file
}

above 以上

fis = openFileInput(FILENAME);

This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one. 这将检查给定FILENAME是否存在File ,如果不存在,它将创建一个新文件。

If you're working on Android , why don't you use the API's solution for saving files ? 如果您使用的是Android ,为什么不使用API的解决方案来保存文件

Quoting: 引用:

String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data . 您应该真正阅读整个文档,它们很好地解释了创建或访问文件的基本方法,还可以检查存储数据不同方法

But regarding your original question: 但是关于您的原始问题:

So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want? 因此,如果我将保存数据代码添加到正在加载数据部分的“ FileNotFoundException”捕获中,那么我可以实现我想要的吗?

Yes, you could achieve it. 是的,您可以实现。

Try this one: 试试这个:

public static void readData() throws IOException
{
    File file = new File(path, filename);
    if (!file.isFile() && !file.createNewFile()){
        throw new IOException("Error creating new file: " + file.getAbsolutePath());
    }

    BufferedReader r = new BufferedReader(new FileReader(file));
    try {
        // ...
        // read data
        // ...
    }finally{
        r.close();
    }
}

Ref: Java read a file, if it doesn't exist create it 参考: Java读取文件,如果不存在则创建它

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

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