我创建了一个包含 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/