[英]BufferedReader not reading complete .txt file
我正在嘗試將中等大小的txt文件(65,00個單詞)讀入字符串,然后是字符串數組。 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;
}
}
用這種方式做。 如果要讀取整個文件,請刪除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")
獲取系統特定的行分隔符 readLine將讀取文檔的第一行。 嘗試一下(未測試):
String lineReaded;
while ((lineReaded=brFile.readLine())!=null)
{
record +=linereaded+"\n";
}
尼可
您可能想使用Files.readAllLines
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.