将整数值写入文件并读取它

时间:2014-02-25 19:06:06

标签: java file-io

我的twitch.bot中有一个Follower-check功能,我需要一个读/写解决方案。

应该执行以下操作:

从文件中读取给定的Number(int) 将新号码写入文件并删除旧号码 如果文件不存在,则创建该文件

(文件只需要存储1个号码)

那我怎么能这样做呢?

现在,我有一个字符串阅读器,我一读到它就把它解析成一个INT,但我只有错误,所以我认为它不会那样工作所以我正在搜索一个选项来写/读已经没有从字符串中解析它。

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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

它似乎比它应该更复杂。如果您只想编写一个数字而不将其解析为文本,则可以执行此操作。

BTW您也可以使用long因为它将使用相同的磁盘空间并存储更多范围。

public static void writeLong(String filename, long number) throws IOException {
    try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
        dos.writeLong(number);
    }
}

public static long readLong(String filename, long valueIfNotFound) {
    if (!new File(filename).canRead()) return valueIfNotFound;
    try (DataInputStream dis = new DataInputStream(new FieInputStream(filename))) {
        return dis.readLong();
    } catch (IOException ignored) {
        return valueIfNotFound;
    }
}
相关问题