package employee;
import employee.nidhin.staples;
import java.util.*;
import java.io.*;
public class Employee {
public static void main(String[] args)
{
int j=3;
staples[] stemp = new staples[j];
String file_name = "d:/personal/11636470/NetBeansProjects/Employee/src/employee/Xanadu.txt";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for ( j=0;j<3;j++)
{
stemp[j] = new staples();
System.out.print("Enter your name : ");
stemp[j].setName(reader.readLine());
System.out.println("Enter your age : ");
stemp[j].setAge(Integer.parseInt(reader.readLine()));
}
for ( j=0;j<3;j++)
{
System.out.println("Employee number:" + j +" name:"+stemp[j].getName()+" Age:"+stemp[j].getAge() );
}
reader.close(); // VERY IMPORTANT TO CLOSE
System.out.println("Now writing the file to Xanadu.txt ");
PrintWriter out = new PrintWriter(
new FileWriter("file_name"));
for (int i = 0; i < 3; i++)
{
out.println("Value at: "+ i + " = "+ stemp[i].getName());
}
System.out.println("Successfully wrote to file");
out.close();
}
catch(java.io.IOException ex)
{
System.out.println("Error is " + ex.getMessage() );
}
}
}
程序执行成功,但是当我打开输出文件Xanadu.txt时,我什么也看不见。有人可以指导我吗? Xanadu.txt文件的内容是一个stemp对象数组,它有两个属性name和age。
答案 0 :(得分:0)
file_name
周围不得有引号。如果你把它们放在一边,它会被解释为一个字符串,并且数据被写入工作目录中名为“file_name”的文件中。
PrintWriter out = new PrintWriter(
new FileWriter(file_name));
......会是正确的
答案 1 :(得分:0)
PrintWriter out = new PrintWriter(new FileWriter("file_name"));
你传递的字符串是:“file_name”, 试着这样做:
PrintWriter out = new PrintWriter(new FileWriter(new File(file_name)));
我认为它应该有效。由于FileWriter构造函数应该将File作为参数,我认为。
答案 2 :(得分:0)
最好的方法就是让它变得简单:尝试下面的代码:
fos=new File(filepath);
if(fos.exists() && fos.isFile() && !fos.isDirectory())
{
FileWriter fw=new FileWriter(fos);
BufferedWriter Bw= new BufferedWriter(fw);
Bw.append("i am appending text to the existing file");
}
如果你想通过创建新文件进行编写,那么首先进行文件搜索,如果不存在,则使用以下内容创建和写入数据:
fos=new File(filepath);
if(!fos.exists() && !fos.isFile())
{
FileWriter fw=new FileWriter(fos);
BufferedWriter Bw= new BufferedWriter(fw);
Bw.write("i am writing text to the existing file");
}