用arraylist数组存了一些学生对象 学生对象有三个属性 姓名 学号 爱好。现在想把这些学生对象格式化的输出到一个txt中。格式如下姓名   学号    爱好
a        01     篮球
b       02      足球
c       03      台球
。。
  中间省略。。这些字符之间都是用\t来控制格式的 不是空格。
好像有一个类可以控制 
哪位知道?帮小弟一把

解决方案 »

  1.   

    这个要自己写一个方法:
    void writeToFile(ArrayList<Student> sList){
       BufferedWriter bw=new BufferedWirter(new OutputStreamWirter(new FileOutputStream(),"UTF-8"));
       for(Student s : sList){
          String str=s;
          bw.write(str,0,str.length());
          bw.newLine();
       }
       bw.flush();
       bw.close();
     }
    为了达到输出的预期并使下面的语句能执行,你还要在Student类中重写toString()方法.
    String str=s;
      

  2.   

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintWriter;
    import java.util.ArrayList;public class Test { /**
     * @param args
     */
    public static void main(String[] args) {

    ArrayList list = new ArrayList<Student>();

    Student s1 = new Student("a","01","篮球 ");

    Student s2 = new Student("b","02","篮球 ");

    Student s3 = new Student("c","03","台球  ");

    list.add(s1);

    list.add(s2);

    list.add(s3);

    PrintWriter pw = null;
    try {
    pw = new PrintWriter(new FileOutputStream("d:\\a.txt"),true);
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    if(pw != null){
    pw.println("姓名\t学号\t爱好");
    for (Object object : list) {
    Student student = (Student)object;
    pw.println(student.getName()+"\t"+student.getNumber()+"\t"+student.getHobby());


    }
    }
    }}
    结果:a.txt:姓名 学号 爱好
    a 01 篮球 
    b 02 篮球 
    c 03 台球  
      

  3.   

    大致思想如下:用到util包的ArrayList类,IO包,写文件,还有自定义一个Student类
    Student类提供相应字段,相应的get set 访问器.代码楼上的已经实现。
      

  4.   

    Student 类重写 toString 方法,方法中使用 \t 拼接属性值
      

  5.   


    Student 类重写 toString 方法,小弟不才,请问该句有如何用处?
      

  6.   

    某个类不继承任何类,为什么写了toString 就是重写?为什么给String赋值的时候,会自动调用?
      

  7.   

    不集成 任何 类 那就只能继承object 不叫重写,
    可以直接调用,调用父类的 方法啊
      

  8.   

    某个类不继承任何类?不可能,任何类都是Object子类,toString()是Object的方法