簡體   English   中英

如何使該程序寫入文件?

[英]How do I get this program to write to a file?

我可以使用該程序在正確的文件夾中創建一個文件,並且在我的讀取文件中,我可以讀取文本(如果已預先編寫的話)。 但是,我似乎無法將其寫入並保存到文件中,而且我不確定此處缺少什么。 任何幫助將不勝感激!

import java.nio.file.*;
import java.io.*;
import static java.nio.file.AccessMode.*;
import java.util.Scanner;

public class WriteEmpList
{
   public static void main (String[] args)
   {
      Path file=Paths.get("C:\\Java\\EmployeeLists.txt");
      Scanner in=new Scanner(System.in);
      String[] array =new String[3];
      String s=" ";
      String firstName,lastName,id;
      try 
      {
         OutputStream output=new BufferedOutputStream(Files.newOutputStream(file));
         BufferedWriter writer= new BufferedWriter(new OutputStreamWriter(output));

         System.out.println("Enter ID number or 999 to quit");

         id=in.nextLine();

         while (!id.equals("999"))
         {
            System.out.println("Enter first name");
            firstName=in.nextLine();
            System.out.println("Enter last name");
            lastName=in.nextLine();

            s=id+","+firstName+","+lastName+System.getProperty("line.separator");
            writer.write(s,0,s.length());

            System.out.println("Enter id number or 999 to quit: ");
            id=in.nextLine();
         }
      }
      catch(Exception e)
      {
         System.out.println("Error: "+e);
      }  
   }
}

有幾種方法可以做到這一點,但是您應該始終關閉流。

如果您只想簡單地將文本寫入文件,則可以使用更簡單的方法,例如PrintWriter:

PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(some text);
writer.close();

一些替代方法在此處提供文檔: https : //docs.oracle.com/javase/tutorial/essential/io/file.html

使用try {} catch {}塊作為

 try 
  {
     output=new BufferedOutputStream(Files.newOutputStream(file));
      writer= new BufferedWriter(new OutputStreamWriter(output));

     System.out.println("Enter ID number or 999 to quit");

     id=in.nextLine();

     while (!id.equals("999"))
     {
        System.out.println("Enter first name");
        firstName=in.nextLine();
        System.out.println("Enter last name");
        lastName=in.nextLine();

        s=id+","+firstName+","+lastName+System.getProperty("line.separator");
        writer.write(s,0,s.length());

        System.out.println("Enter id number or 999 to quit: ");
        id=in.nextLine();
     }
    writer.close();

  }
  catch(Exception e)
  {
     System.out.println("Error: "+e);
  }

在try塊結束之前的while循環結束之后添加以下兩行代碼。

        .
        .
        .
        System.out.println("Enter id number or 999 to quit: ");
        id=in.nextLine();
     }
     writer.close();
     output.close();
  }
  catch(Exception e)
  {
      .
      .
      .

基本上,您需要關閉緩沖區和流才能將輸出寫入文件中。

暫無
暫無

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

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