繁体   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