我有這個程序,讓你打開一個文件,並將其一次全部使用下面的代碼到一個JTextArea
讀它:一次添加一行到字符串
try{
String fileContents = new Scanner(new File(fileName)).useDelimiter("\\Z").next();
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
和工作原理。但我的問題是,我怎樣才能將這個讀入我的fileContents
字符串中,並且每當我換行符時仍然會在換行符中添加它?
這裏是我有什麼,但是這使這一切在一條線在我的textarea:
try{
Scanner contentsTextFile = new Scanner(new File(fileName));
while(contentsTextFile.hasNext()){
fileContents = contentsTextFile.useDelimiter("\r\n|\n").nextLine();
}
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
我想看到的是使用一個分隔符,只有讀入這一行文字中取得了新的生產線一次一行,而不是整個文件。
有人可以幫忙嗎?
是的,這是我決定我會做的。我使用'FileReader'和'BufferedReader'獲取文件內容,然後使用'myTextArea.append(contents)'一次將它們追加到'JTextArea';' –
+1但JTextComponent.read/write接受文件中的分隔符(雙向I/O) – mKorbel
@mKorbel:同意對'文檔'進行不可分割的操作。除了Scanner外! :-) – trashgod