java BufferedReader读取未完成。txt文件
我试图将一个中等大小的txt文件(65,00个单词)读入一个字符串,然后读入一个字符串数组。bufferedreader抛出“无法读取文件”捕获。当我清除它时,文本文件的一小部分内容会显示在系统中。出来我没有在较小的文本文件中遇到错误。我是个初学者,在缩小问题范围方面遇到了很多困难
为什么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;
}
}
# 1 楼答案
readLine将读取文档的第一行。 试用(未经测试):
妮可
# 2 楼答案
你可能想用Files.readAllLines
# 3 楼答案
这样做。如果要读取整个文件,请删除
reset()
和mark()
方法注:
System.getProperty("line.separator")
获取系统特定的行分隔符看看Java7 try-with-resources Statement advantage