我可以让这个程序在正确的文件夹中创建一个文件,在我的阅读文件中,如果文本已经预先编写,我可以阅读它。但是,我似乎无法将其写入并保存到文件中,我不确定我在这里缺少什么。任何帮助将非常感谢!
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);
}
}
}
答案 0 :(得分:1)
有几种方法可以执行此操作,但您应始终关闭该流。
如果你只想简单地将文字写入文件,那么有更简单的方法,比如PrintWriter:
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(some text);
writer.close();
这里有一些备选方案:https://docs.oracle.com/javase/tutorial/essential/io/file.html
答案 1 :(得分:0)
使用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);
}
答案 2 :(得分:0)
在try块结束之前的while循环结束后添加以下两行代码。
.
.
.
System.out.println("Enter id number or 999 to quit: ");
id=in.nextLine();
}
writer.close();
output.close();
}
catch(Exception e)
{
.
.
.
基本上你需要关闭缓冲区和输出流以便写入文件。