簡體   English   中英

如何使用Java創建的“使用鍵盤和PrintWriter類”寫入txt文件

[英]How to write to a txt file “using the keyboard and PrintWriter Class ” created in 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());
        }
    }

您的代碼未執行,因為您沒有在write方法中刷新PrintWriter資源。 您的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

使用System.in作為InputStream創建一個Scanner

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流,從而使您的方法本質上更具聲明性 因此,修改后的read()方法如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM