尝试检查是否已创建具有相同名称的文本文件

时间:2016-04-05 11:01:28

标签: java android android-studio

我正在尝试创建一个基本应用程序,我在其中输入文本到应用程序,此文本命名一个文本文件,然后该应用程序将额外的文本添加到该文件。如果已经存在具有相同名称的文本文件,我想输出“file exists”。从我可以看到的那一刻,检查是否已经存在具有相同名称的文件是不起作用的。谁能明白为什么?从我看来它应该工作。这是代码:

package com.example.user.filetest;

import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;

public class MainActivity extends AppCompatActivity {

FileUtility myFile = new FileUtility();
private File root;
private File file;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final EditText enter = ((EditText) findViewById(R.id.editText));
    final TextView show = ((TextView) findViewById(R.id.textView));
    Button b = ((Button) findViewById(R.id.button));
    b.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             final String s = enter.getText().toString();
             file = new File(root, "//" + s);
             if (file.exists()) {
                 show.setText("File Exists");
             }
             else {
                 myFile.createFile(getApplicationContext(), s);
                 myFile.writeLine("test");
                 show.setText(myFile.readAll());
             }
         }
     }
    );
}
 package com.example.user.filetest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.content.*;

public class FileUtility {

private File root;
private File file;

public FileUtility() {
    root = Environment.getExternalStorageDirectory();
}

public void createFile(Context context, String fileName) {
    try {
        if (root.canWrite()) {
            file = new File(root, "//" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        }
        else
        {
            file = new File(context.getFilesDir(), "//" + fileName); // File(root, "//" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        }
    } catch (IOException e) {
        Log.e("Error", "fail to create a new file");
    }

}


public String readAll() {
    StringBuilder returnString = new StringBuilder();
    try {
        BufferedReader in;
        FileReader datawriter = new FileReader(file);
        in = new BufferedReader(datawriter);
        if (file.exists()) {
            String str = null;
            while((str=in.readLine())!=null)
            {
                returnString.append(str + "\n");
            }
        }
        in.close();
    } catch (IOException e) {
        Log.e("Error", "fail to write file");
    }
    return returnString.toString();
}

public void writeLine(String message) {
    try {
        BufferedWriter out;
        FileWriter datawriter = new FileWriter(file,true);
        out = new BufferedWriter(datawriter);
        if (file.exists()) {
            out.write(message + "\n");
            out.flush();
        }
        out.close();
    } catch (IOException e) {
        Log.e("Error", "fail to write file");
    }
}

}

1 个答案:

答案 0 :(得分:3)

您在两个类中声明和初始化File root的方式存在问题。

在MainActivity中:

File root属性未初始化

将您的代码更改为

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    root = Environment.getExternalStorageDirectory(); // Initialilze the root file here
    // ...

     b.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             final String s = enter.getText().toString();
             file = new File(root, "//" + s);
             if (file.exists()) {
                 show.setText("File Exists");
             }
             else {
                 myFile.createFile(root, getApplicationContext(), s);  // pass the root file as parameter
                 myFile.writeLine("test");
                 show.setText(myFile.readAll());
             }
         }
     }
);
}

在FileUtility中:

由于您还在FileUtility中使用root来创建新文件,您可以将其作为参数传递,然后删除class属性。

class FileUtility{

   private File file;

   public FileUtility() {
   }

   public void createFile(File root, Context context, String fileName){
      // Use the root initialized into the main activity 
      //...

而你