在文件中添加一个段落

时间:2014-09-08 14:07:15

标签: java api io

我想用文件写一个段落。

这是我的代码(我的努力)。

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();
        }
    }
}

使用此代码我只能添加一个单词,但我想添加很多单词(段落)。

2 个答案:

答案 0 :(得分:0)

我会在Scanner#hasNextLine()周围使用while循环。我还建议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();
    }
}

答案 1 :(得分:0)

为了编写一个段落,决定一个终止字符或字符串,编写你的代码,直到输入中输入该字符或字符串,执行一些操作来删除文件中的字符, 我使用的代码如下,Terminating Character是+ 我没有继续尝试并抓住陈述来降低理解的复杂性

    pw = new PrintWriter(new FileWriter("E://files//myfile.txt"));   
    System.out.println("Write the Text in the File,End the text with + ");
    do
    {
        Scanner sc =new Scanner(System.in);
        String S=sc.nextLine();
        if(S.endsWith("+"))
        {
           S= S.replace("+"," ");
            flag=1;
            pw.println(S);
        }
        else
            pw.println(S); 
    }while(flag!=1);

干杯