我在我的twitch.bot中有一个跟踪检查函数,我需要一个读写解决方案。
它应做以下工作:
从文件中读取给定的数字(Int),将一个新的数字写入文件,删除旧的数字,如果文件不存在,创建该文件
(文件只需要存储一个号码)
那我该怎么做呢?
现在,我有一个string,我一读它,就把它解析成INT,但是我只看到错误,所以我认为它不是那样工作的,所以我搜索一个选项来编写/读取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();
}
}
}
发布于 2014-02-25 11:18:29
它看起来比它应该要复杂得多。如果您只想编写一个数字而不将其解析为文本,那么您可以这样做。
顺便说一下,您可以使用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;
}
}
https://stackoverflow.com/questions/22023777
复制相似问题