2014-02-11 4 views
0

Это мой первый пост, поэтому я извиняюсь, если это не лучший формат. Я участвую в написании кода для импорта документа, чтения строки в документе, а затем разворачивания букв в каждом слове. Новое слово будет напечатано в новом файле. Например, «Jon 123» будет храниться и записываться как «321 noJ». Я получил вход для работы, но есть проблема с написанием строки. Программа записывает только последнее слово, которое хранится.Использование цикла while для записи файла

Сокращенный основной код метод заключается в следующем:

//get first line of text 
    line = bw.readLine(); 

    //while string is not null 
    while (line != null) 
    { 
     System.out.println ("Processing..."); //display message to show work being done 

     tokenLine = lineToken(line); //tokenize string 

     //to prevent exception from no token found 
     while (tokenLine.hasMoreTokens()) 
     { 
      word = flipWord(tokenLine);  //get next token and reverse letters 
      newLine = marginCheck(word); //store or write line depending on margin 

      flushClose(newLine); //write and flush buffer then close file 
     } 


     //move to next line in file 
     line = bw.readLine(); 
    } 

    flushClose(newLine); //write and flush buffer then close file 

    //output completion message 
    System.out.println("The new file has been written."); 

Соответствующие методы следующим образом:

общественные статические StringTokenizer lineToken (String линия) { // локальные константы

//local variables 
    StringTokenizer tokenLine;  //store tokenized line 

    /******************* Start lineToken Method ***************/ 

    tokenLine = new StringTokenizer(line); //tokenize the current line of text 

    return tokenLine; 

}//end lineToken 

public static String flipWord (StringTokenizer tokenLine) { // локальные константы

//local variables 
    String word;  //store word for manipulation 
    String revWord = "";  //store characters as they are flipped 

    /******************************* Start flipWord Method******************/ 
    //store the next token as a string 
    word = tokenLine.nextToken(); 

    //for each character store that character to create a new word 
    for (int count = word.length(); count > 0; count--)  
     revWord = revWord + word.charAt(count - 1); //store the new word character by character 

    return revWord;  //return the word reversed 

}//end flipWord 

открытая статическая Строка marginCheck (Строка revWord) бросает исключение {// локальные константы конечной INT MARGIN = 60; // максимальное количество символов в строке

//local variables 
    String newLine = "";   //store the new line 
    FileWriter fw;  //writes to output file 
    BufferedWriter bWriter;  //instantiate buffered writer object 
    PrintWriter pw;  //instantiate print writer object 
    String outFile = "RevWord.text"; //file to write to 

    /************* Start marginCheck Method ************/ 
    //open the output file for writing 
    fw = new FileWriter(outFile); 
    bWriter = new BufferedWriter(fw); 
    pw = new PrintWriter(bWriter); 

    //if the buffered line concatenated with the word is less than the margins 
    if (newLine.length() + revWord.length() <= MARGIN) 
     newLine = newLine + revWord + " ";  //the buffered line adds the word 
    else 
     //put an enline character at the end and write the line 
     newLine = newLine + "\n"; 
     pw.println(newLine); 

     //use this word as the first word of the next line 
     newLine = revWord + " "; 
    return newLine;  //return for use with flush 
}//end marginCheck 

государственной статической силы flushClose (String INLINE) бросает исключение { // локальные константы

//local variables 
    FileWriter fw;  //writes to output file 
    BufferedWriter bWriter;  //instantiate buffered writer object 
    String outFile = "RevWord.text"; //file to write to 

    /************ Start flushClose Method *********/ 
    fw = new FileWriter(outFile); 
    bWriter = new BufferedWriter(fw); //initialize writer object 

    //write the last line to the output file then flush and close the buffer 
    bWriter.write (inLine); 
    bWriter.flush(); 
    bWriter.close(); 
}//end flushClose 

ответ

2

Я не уверен, но моя догадка, что каждый раз, вы пишете в файл, вы переписываете файл, а не добавляете его.

Попробуйте FileWriter (outFile, true);

http://www.mkyong.com/java/how-to-append-content-to-file-in-java/

+0

Perfect. Открыли некоторые другие проблемы, но это решает большой. Спасибо. – wizeman02

Смежные вопросы