我知道有很多与此相关的问题,但是我仍然没有遵循。我已从有关如何创建,写入和读取文件的教程中复制了以下代码。有一个CreateFile
类,一个ReadFile
类和一个Demo
类:
CreateFile.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();
}
}
ReadFile.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
从未被创建吗?
答案 0 :(得分:-2)
我建议您研究序列化比写.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;
}
我希望这段代码足够清楚。如果您还有其他问题,请告诉我。我会很乐意回答他们。