2014-09-20 82 views
-1

這是我到目前爲止。它成功讀取第1.txt章節並將它放入book.txt中,但是,我需要讓它接受2個章節,這是我無所適從的地方。有沒有一種方法可以使用FileReader方法來讀取多個文本文件?有沒有一種方法可以使用FileReader方法來讀取多個文本文件?

import java.io.*; import java.util.*; public class CatFiles { public static void main(String[] args) throws FileNotFoundException, IOException { File compiledChapters = new File("Book.txt"); if(!compiledChapters.exists()) { compiledChapters.createNewFile(); } FileReader myReader = new FileReader("chapter 1.txt"); Scanner myScanner = new Scanner(myReader); PrintWriter myWriter = new PrintWriter("Book.txt"); while(myScanner.hasNextLine()) { String textLine = myScanner.nextLine(); myWriter.println(textLine); }
myReader.close(); myWriter.close(); } }

回答

0

一個非常簡單的方法就是做這個

FileReader myReader = new FileReader("chapter 1.txt"); 
Scanner myScanner = new Scanner(myReader); 
PrintWriter myWriter = new PrintWriter("Book.txt"); 
while(myScanner.hasNextLine()) 
{ 
    String textLine = myScanner.nextLine(); 
    myWriter.println(textLine); 
} 
myReader.close(); 

FileReader myReader2 = new FileReader("chapter 2.txt"); 
Scanner myScanner2 = new Scanner(myReader2); 
while(myScanner2.hasNextLine()) 
{ 
    String textLine = myScanner.nextLine(); 
    myWriter.println(textLine); 
} 
myReader2.close(); 

FileReader myReader3 = new FileReader("chapter 3.txt"); 
Scanner myScanner3 = new Scanner(myReader3); 
while(myScanner3.hasNextLine()) 
{ 
    String textLine = myScanner.nextLine(); 
    myWriter.println(textLine); 
} 
myReader3.close(); 

myWriter.close(); 

但是,這是非常醜陋的,可能需要在它的方法自己喜歡

WriteChapter("Chapter 1.txt"); 
WriteChapter("Chapter 2.txt"); 
WriteChapter("Chapter 3.txt"); 
相關問題