我试图将一个中等大小的txt文件(65,00个单词)读入一个String,然后是一个字符串数组。 bufferedreader抛出"无法读取文件"抓住。当我清除它时,文本文件的一小部分内容显示在system.out中。我没有得到较小的文本文件的错误。我是初学者,在尝试缩小问题时遇到了很多麻烦。
为什么BufferedReader没有摄取整个文件?为什么"无法读取文件"错误被抛出?
public class Main {
public static void main(String[] args) {
final Guid Main = new Guid(); //creates instance of Guid
Main.mergeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
merge();
}
});
}
static void merge()
{
//read file and turn into string
String pathone = open(Guid.PathOne);
System.out.print(pathone);
//parse and format
//String[] oneArray = pathone.replace("\n"," ").split(" ");
//get pathtwo text
//String pathtwo = open(Guid.PathTwo);
//parse and format
//load into array
//compare array entries
//add new array entry
//sort array
//write array to paththree file
//for(int i=0; i<oneArray.length;i++)
//{
//System.out.println(oneArray[i]);
//}
}
public static String open(JTextArea Path)
{
String record = null;
FileReader frFile = null;
try {
frFile = new FileReader(Path.getText());//gets file from Path
BufferedReader brFile = new BufferedReader(frFile);//creates buffered reader
record = brFile.readLine() + "\n"; //gets contents of file and puts it into a string
brFile.mark(0);
while (brFile.read() != -1) //loop to read the rest of the text file
{
brFile.reset();
record = record + brFile.readLine() + "\n";
brFile.mark(0);
}
}
catch (FileNotFoundException e) //catch path is in error
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not find file.");
}
catch (IOException e) //catch if file cannot be read
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not read file.");
}
try { //closes file
frFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return record;
}
}
答案 0 :(得分:2)
这样做。如果要阅读整个文件,请删除reset()
和mark()
方法。
StringBuilder record = new StringBuilder();
BufferedReader brFile = new BufferedReader(frFile);
String line = null;
while ((line = brFile.readLine()) != null) {
record.append(line).append("\n");
}
System.getProperty("line.separator")
获取系统特定的行分隔符答案 1 :(得分:1)
readLine将读取文档的第一行。 尝试使用它(未经测试):
String lineReaded;
while ((lineReaded=brFile.readLine())!=null)
{
record +=linereaded+"\n";
}
尼科
答案 2 :(得分:1)
您可能希望使用Files.readAllLines