如何使用键盘和PrintWriter Class"写入txt文件"在java中创建

时间:2017-08-10 17:32:39

标签: java

我创建了一个写入文件的方法但该方法无法执行,因为我在main方法中调用它。如果我可以通过键盘而不是使用PrintWriter资源写入文件,我还想知道要知道什么?

import java.io.*;
import java.util.*;
/**
 *
 * @author toshiba
 */
public  class EXERISESONFILEWRITINGANDREADING {
        File file;

    public static void main(String[] args) throws Exception{
        EXERISESONFILEWRITINGANDREADING obj = new   EXERISESONFILEWRITINGANDREADING();
        obj.Create("D:\\document\\work.txt");
        obj.Write();
        obj.Read();
        }

    public  void Create(String name){ //name implies the directory of your  folder/file.
         file = new File(name); 
    }

    public void Write() throws Exception{
        PrintWriter WRITE = new PrintWriter(file);
        WRITE.print("this is my abode");
        WRITE.print("\nthis is my apartment");
        WRITE.print("\nthis is my Private Jet");
    }
    public void Read() throws Exception{
        Scanner input = new Scanner(file);
        while(input.hasNext()){
            System.out.println(input.next());
        }
    }

1 个答案:

答案 0 :(得分:0)

您的代码未执行,因为您没有在PrintWriter方法中刷新write资源。您的write方法将写入给定文件,您将其更改为:

public void write() throws Exception {
    PrintWriter writer = new PrintWriter(file);
    writer.println("this is my abode");
    writer.println("this is my apartment");
    writer.println("this is my Private Jet");

    writer.flush();
    writer.close();
}

现在,如果您想接受来自键盘的输入,然后将其写入文件,则可以使用Scanner

创建Scanner System.in作为InputStream

Scanner sc = new Scanner(System.in);

创建或使用相同的PrintWriter资源:

PrintWriter writer = new PrintWriter(file);

开始接受键盘输入,直到用户输入一个空行 - ""并将其写入您的文件。

String in = "";
while ( !(in = sc.nextLine()).equals("") ) {
    writer.println(in);
}

最后,整个方法应如下所示:

public void writeToFileFromKeyboard() throws FileNotFoundException {
    Scanner sc = new Scanner(System.in);
    PrintWriter writer = new PrintWriter(file);

    String in = "";
    while ( !(in = sc.nextLine()).equals("") ) {
        writer.println(in);
    }

    sc.close();
    writer.flush();
    writer.close();
}

注意: 这只是一个建议!!

如果您使用的是 Java-8 ,则可以修改read()方法以使用Java-8 Streams,这样您的方法就会变得更加declarative in nature。因此,修改后的read()方法如下所示:

public void read() throws Exception {
    Files.lines( Paths.get(filePath) )
         .forEach( System.out::println );
}