2014-09-08 4 views
1

Я хотел бы написать абзац, используя файл.Добавить абзац в Файл

Это мой код (мои усилия).

import java.io.*; 
import java.util.Scanner; 

public class Test { 
    public static void main (String [] args) 
    { 
     Scanner input = new Scanner(System.in); 
     try { 

      BufferedWriter out = new BufferedWriter(new FileWriter("C:/Users/Akram/Documents/akram.txt")) ; 
      System.out.println("Write the Text in the File "); 
      String str = input.nextLine(); 
      out.write(str); 
      out.close(); 
      System.out.println("File created successfuly"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

С помощью этого кода я могу добавить только одно слово, но хочу добавить много слова (параграф).

+0

nextLine() должен предоставить вам весь контент с вашего ввода до нового символа строки (\ n). Ваш абзац содержит новые строковые символы? – prabugp

ответ

0

Я бы использовал цикл while вокруг Scanner#hasNextLine(). Я бы также рекомендовал PrintWriter. Итак, все вместе, это будет выглядеть примерно так:

Scanner input = new Scanner(System.in); 
PrintWriter out = null; 
try { 
    out = new PrintWriter(new FileWriter(
      "C:/Users/Akram/Documents/akram.txt")); 
    System.out.println("Write the Text in the File "); 
    while (input.hasNextLine()) { 
     String str = input.nextLine(); 
     out.println(str); 
    } 
    System.out.println("File created successfuly"); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    if (out != null) { 
     out.close(); 
    } 
} 
Смежные вопросы