java - 创建、写入和读取文件
问题描述
我知道有很多与此相关的问题,但我仍然没有关注。我从有关如何创建、写入和读取文件的教程中复制了以下代码。有一个CreateFile
类,一个ReadFile
类,一个Demo
类:
创建文件.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("chinese.txt");
}
catch(Exception e)
{
System.out.println("You have an error");
}
}
public void addRecords(){
x .format("%s%s%s", "20 ", "bucky ", "robers");
}
public void closeFile(){
x.close();
}
}
读取文件.java
public class ReadFile {
private Scanner x;
public void openFile()
{
try{
x = new Scanner(new File("words.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile()
{
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
x.close();
}
}
public class Demo {
public static void main(String[] args) {
CreateFile g = new CreateFile();
g.openFile();
g.addRecords();
g.closeFile();
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
}
如果Demo.java
我删除与读取文件相关的最后四个语句,则与打开和写入文件相关的前四个语句运行没有错误。但是,一旦我添加
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
并运行程序,它会输出:Exception in thread "main" could not find file.
我不确定发生了什么,文件是否chinese.txt
从未被创建?
解决方案
我建议您研究序列化它比写入 .txt 文件更容易和简单。
但是如果你真的需要做 .txt 文件,这就是你写入 .txt 文件的方式
//This gets your project directory
private String projectPath = System.getProperty("user.dir");
//call save()
String save("test.txt", "This is will be save to a test.txt file");
private boolean save(String textfile String outputtext){
String filepath = projectPath + textfile;
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath));
writer.write(outputtext);
writer.close();
} catch(IOException e) { }
return true;
}
这就是你阅读它的方式
private String load(String textfile){
String temp="";
String filepath = projectPath + textfile;
try{
BufferedReader reader =new BufferedReader(new FileReader(filepath));
while(true){
//this will read one line at a time you can append it output
try {
temp+= reader.readLine();
//If no more lines break out of the loop
if(line==null)
break;
}catch(IOException e){}
}
reader.close();
}
catch(IOException e){}
//Return contents of the file you loaded
return temp;
}
我希望这段代码足够清晰。如果您还有任何问题,请告诉我。我很乐意回答他们。
推荐阅读
- gps - 让 GPS 模块给出正确的值(很可能是缓冲区问题)
- saxon - 撒克逊人容易受到 XXE 攻击吗?
- c++ - Homebrew OS X OpenCV - 在另一台 Mac 上运行时寻找 dylib
- excel - 绕过公式数组
- c# - 使用 LINQ 时出现 StackOverFlow 未处理错误”
- regex - 通配符或等效于在 excel 文件中读取
- python - 将列附加到新数据框
- powershell - 在 Post Always 部分发布 Nunit 测试结果
- ruby-on-rails - devise-token-auth sign_up 的自定义注册路由
- python - 在 python 中调用 .describe 函数时,如何规范化列?我想要 2 位小数的输出