我试图制作两个能够读写文本文件的对象。执行程序时会出现问题。文本文件被删除。为什么会发生这种情况?如何解决这个问题?
CODE:
读取文本文件的对象:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Reader {
public static String fromFile;
public static FileReader fr;
public static BufferedReader file;
public Reader(String fileName) throws IOException, FileNotFoundException {
fr = new FileReader(fileName);
file = new BufferedReader(fr);
}
public void readFile() throws IOException {
while((fromFile = file.readLine()) != null) {
System.out.println(fromFile);
}
}
}
要写入文本文件的对象:
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class Writer {
public static FileWriter fw;
public static BufferedWriter file;
public Writer(String fileName) throws IOException, FileNotFoundException {
fw = new FileWriter(fileName);
file = new BufferedWriter(fw);
}
}
创建Reader和Writer对象并使用Reader读取文本文件的主要方法:
import java.io.IOException;
public class Main {
public static Writer toFile;
public static Reader fromFile;
public static String fileName = "test123.txt";
public static void main(String[] args) throws IOException {
toFile = new Writer(fileName);
fromFile = new Reader(fileName);
fromFile.readFile();
}
}
答案 0 :(得分:0)
这只是我的建议。
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
public static String fileName = "test123.txt";
Read rd=new Read();
rd.reader(filename);
}
}
public class Read
{
public void reader(String filename)
{
FileReader fr=new FileReader(filename);
BufferedReader bfr=new BufferedWriter (fr);
String text="";
String line=reader.readLine();
while(line!=null)
{
text+=line;
line=reader.readLine();
}
System.out.println(text);
}
fr.close();
bfr.close();
}