0
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。

4

3 回答 3

0

周围不能有引号file_name。如果你把它们放在周围,它会被解释为一个字符串,并且数据被写入工作目录中一个名为“file_name”的文件。

PrintWriter out = new PrintWriter(
new FileWriter(file_name));

...应该是正确的

于 2012-02-04T18:50:36.577 回答
0
PrintWriter out = new PrintWriter(new FileWriter("file_name"));

您正在传递一个字符串,上面写着:“file_name”,请尝试这样做:

PrintWriter out = new PrintWriter(new FileWriter(new File(file_name)));

我认为它应该工作。我认为,作为 FileWriter 构造函数应该将 File 作为参数。

于 2012-02-04T18:54:43.720 回答
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");
}
于 2016-02-27T09:58:21.853 回答