2014-09-20 79 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"); 
相关问题