Java:读/写文件等

标签 java bufferedreader java-io

我创建了一个包含 2 个方法的类,它们应该处理在文件中写入或从文件中读取。

我想出了这样的东西:

package YBot;
import java.io.*;



public class FollowerChecker {



public static StringBuilder sb;


    static String readFile(String fileName) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        try {
            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();

            }
            return sb.toString();
        } finally {
            br.close();

        }
    }



    public static void Writer() {

        FileWriter fw = null;

        try {
            fw = new FileWriter("donottouch.txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        StringWriter sw = new StringWriter();
        sw.write(TwitchStatus.totalfollows);


        try {
            fw.write(sw.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        try {
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

现在我的问题是:

如果“donottouch.txt”文件尚不存在或为空,无法在其中写入“0”,我如何添加创建“donottouch.txt”文件的功能?当我的程序启动时,它将读取文件中的数字,然后,如果数字发生更改,它将重写它。因此,最好的办法是,一旦它尝试读取但它不存在,它就会立即创建它并重新读取它。希望 some1 能给我一些例子 =)

最佳答案

这是我的处理方法:

public static boolean checkIfExists(String path) {
    if (!new File(path).exists()) {
        return false;
    } else {
        return true;
    }
}

public static String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String line;
    StringBuilder sb = new StringBuilder();

    while( ( line = reader.readLine() ) != null) {
        sb.append( line );
    }
    reader.close();
    return sb.toString();

}

public static void writeFile(String path) throws FileNotFoundException, 
                                                UnsupportedEncodingException {
    PrintWriter writer = new PrintWriter(path, "UTF-8");
    writer.println("0");
    writer.close();
    return;
}

public static void main(String args[]) {
    /*Gets absolute path to your project folder, assuming that is where
     * you are storing this text file. Otherwise hard code your path
     * accordingly.
     */
    File file = new File("");
    String fileGet = file.getAbsolutePath();
    StringBuilder sb = new StringBuilder();
    String path = sb.append(fileGet.toString() + "/donottouch.txt").toString();

    String result=null;

    if(!checkIfExists(path)) {
        try {
            writeFile(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("File created: 'donottouch.txt'");

    } else {
        try {
            result = readFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if( result.length() == 0 ) {
            try {
                writeFile(path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println("File amended: 'donottouch.txt'");
        }
        System.out.println("File exists: 'donottouch.txt'");
    }
}

显然,我创建了一个主类,并在类之外完成了所有这些操作,这与您不同,但集成起来应该非常简单。假设您将“donottouch.txt”存储在项目的源文件中,但是您可以轻松更改获取您正在查找的文件夹的硬编码路径的绝对路径的代码片段。希望这有帮助!

关于Java:读/写文件等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22019296/

相关文章:

java - `TimeoutException` 和 `CancellationException` 之间的区别

java - 在 Eclipse 中放置配置文件的正确位置

java - 缓冲读取器找到特定的行分隔符然后读取该行

java - 如何在 Java 中存储文本文件字符串以供以后使用

java - 如何使用 Java 按图 block 读取 TIFF 文件?

java - JDK 8 的类型推断如何与泛型一起工作?

java - 从文本文件读取时出错

java - FileInputStream.read(byte[]) 有什么问题?

java - 在Java中修改二进制文件的内容

java - AndEngine 的 GenericPool 处理 6 个 Sprite