麻烦在java中写入文件

时间:2014-06-12 03:44:12

标签: java writer

嘿我试着写一个文件,但我在它写入行进入文本文件的每一行的行上得到一个错误,无法弄清楚任何帮助将不胜感激 作家代码  

 public static void stuIDWrite() throws IOException
 {
     Writer writer = null;

 try {
     writer = new BufferedWriter(new OutputStreamWriter(
           new FileOutputStream("Res/stuIDSorted.txt")));
 } catch (IOException ex) {
   // report
 } finally {
    try {writer.close();} catch (Exception ex) {}
 }
 int i = 0;

    while (i <= stuArrayIdSort.length + 1)
    {
        ln = stuArrayIdSort[i].getStuLastName();    
        fn = stuArrayIdSort[i].getStuFirstName();
        pn = stuArrayIdSort[i].getStuFirstName();
        id = stuArrayIdSort[i].getStuId();
        ft = stuArrayIdSort[i].getFTime();
        phn =stuArrayIdSort[i].getPhoneNum();
        lj = stuArrayIdSort[i].getLovJava();
        con = stuArrayIdSort[i].getCont();
            writer.write(ln + "," + fn + "," + pn  + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
            writer.close();
            i++;    
    }

完整代码

import java.io.*;
import java.util.*;
public class StudentMain {
    /**
     * @param args
     */

        //array and sorting variables
     public static studentConstructor[] stuArrayOrig = new studentConstructor[23];
     private static studentConstructor[] stuArrayIdSort = new studentConstructor[23];
     private static studentConstructor[] stuArrayNameSort = new studentConstructor[23];
     private static int lineCount = 0;
     private static int nElms = 0;

     //writer


     //studentConstructor variables 
        public static String fn; //First Name
        public static String ln; //Last Name
        public static String pn; //Preferred Name
        public static int id;     //Student Id Number
        public static boolean ft;//Full-time Boolean
        public static int phn;   //Student Phone Number
        public static boolean lj;//Loving java Boolean
        public static String con;//Continuing 


        File idSort = new File("stuListSortID.txt");


     public static void StuRead()
     {

        Scanner inFile = null;

         try
         {
             inFile = new Scanner
                    (new FileReader("Res/students.txt"));
         }
         catch (FileNotFoundException e)
         {
             // TODO Auto-generated catch block
             System.out.println("File Not Found");
             e.printStackTrace();
         }

            while (inFile.hasNextLine()){
                        inFile.useDelimiter(",|\\n"); //breaks the lines into single info

                        ln = inFile.next();
                            System.out.println(ln);

                        fn = inFile.next();
                            System.out.println(fn);

                        pn = inFile.next();
                            System.out.println(pn);

                        id = inFile.nextInt();
                            System.out.println(id);

                        ft = inFile.nextBoolean();
                            System.out.println(ft);

                        phn = inFile.nextInt();
                            System.out.println(phn);

                        lj = inFile.nextBoolean();
                            System.out.println(lj);

                        con = inFile.next();
                            System.out.println(con);

                            studentConstructor st = new studentConstructor(ln, fn, pn, id, ft, phn, lj, con);
                            stuArrayOrig[lineCount] = st;
                            inFile.nextLine();
                            System.out.println(stuArrayOrig[lineCount]);


                        lineCount++;
                    }
            //setting info into other arrays
            stuArrayIdSort = stuArrayOrig;
            stuArrayNameSort = stuArrayOrig;            

            System.out.println("orig array length" + stuArrayOrig.length);
            System.out.println("id array length" + stuArrayIdSort.length);
            System.out.println("name array length" + stuArrayNameSort.length);
            System.out.println("number of file lines" + lineCount);




            inFile.close(); 


    }    

     public static void stuIdSort()
     {
         studentConstructor temp;
         boolean sorted = false;

         while (sorted == false)
         {  sorted=true;
            for (int i=0; i<stuArrayIdSort.length-1 ; i++)
            {
                if(stuArrayIdSort[i].getStuId() > stuArrayIdSort[i+1].getStuId())
                {
                    temp = stuArrayIdSort[i+1];
                    stuArrayIdSort[i+1] = stuArrayIdSort[i];
                    stuArrayIdSort[i] = temp;
                    sorted=false;

                }
            }
        }
         for(int i=0; i<stuArrayIdSort.length; i++)
         {
             int getSC = stuArrayIdSort[i].studentId;
             System.out.println("number of swaps " + i+1 +" " +getSC);
         }
     }

    //stuArrayIdSort[i].getStuLastName(),stuArrayIdSort[i].getStuFirstName(),stuArrayIdSort[i].getPrefName(),stuArrayIdSort[i].getStuId(),stuArrayIdSort[i].getFTime(),stuArrayIdSort[i].getPhoneNum(),stuArrayIdSort[i].getLovJava(),stuArrayIdSort[i].getCont()
     public static void stuIDWrite() throws IOException
     {
         Writer writer = null;

         try {
             writer = new BufferedWriter(new OutputStreamWriter(
                   new FileOutputStream("Res/stuIDSorted.txt")));
         } catch (IOException ex) {
           // report
         } finally {
            try {writer.close();} catch (Exception ex) {}
         }
         int i = 0;

            while (i <= stuArrayIdSort.length + 1)
            {
                ln = stuArrayIdSort[i].getStuLastName();    
                fn = stuArrayIdSort[i].getStuFirstName();
                pn = stuArrayIdSort[i].getStuFirstName();
                id = stuArrayIdSort[i].getStuId();
                ft = stuArrayIdSort[i].getFTime();
                phn =stuArrayIdSort[i].getPhoneNum();
                lj = stuArrayIdSort[i].getLovJava();
                con = stuArrayIdSort[i].getCont();
                    writer.write(ln + "," + fn + "," + pn  + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
                    writer.close();
                    i++;    
            }
     }

     public static void stuNameSort()
     {

     }

     public static void stuNameWrire()
     {

     }
}
//lastName, firstName, perName, studentId, fulltime,

3 个答案:

答案 0 :(得分:2)

好的,这是你应该做的:

发生的事情是你在实际做任何事情之前关闭它。所以,让我们将你的finally子句移到一切的结尾:

public static void stuIDWrite() throws IOException
 {
     Writer writer = null;

 try {
     writer = new BufferedWriter(new OutputStreamWriter(
       new FileOutputStream("Res/stuIDSorted.txt")));

 int i = 0;

while (i <= stuArrayIdSort.length + 1)
{
    ln = stuArrayIdSort[i].getStuLastName();    
    fn = stuArrayIdSort[i].getStuFirstName();
    pn = stuArrayIdSort[i].getStuFirstName();
    id = stuArrayIdSort[i].getStuId();
    ft = stuArrayIdSort[i].getFTime();
    phn =stuArrayIdSort[i].getPhoneNum();
    lj = stuArrayIdSort[i].getLovJava();
    con = stuArrayIdSort[i].getCont();
        writer.write(ln + "," + fn + "," + pn  + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
        i++;    
}
} catch (IOException ex) {
   // report
  } finally {
try {writer.close();} catch (Exception ex) {}
 }

答案 1 :(得分:0)

我不确定你是怎么理解的......抓住...终于有效了。这就是你拥有的:

     Writer writer = null;

     try {
         writer = new BufferedWriter(new OutputStreamWriter(
               new FileOutputStream("Res/stuIDSorted.txt")));
     } catch (IOException ex) {
       // report
     } finally {
    >>>>>>>  **try {writer.close();} catch (Exception ex) {}**
     }
     int i = 0;

        while (i <= stuArrayIdSort.length + 1)
        {
           //bunch of stuff
                writer.write(...);
    >>>>>>>    **writer.close();**
                i++;    
        }
 }

在你使用它之前关闭编写器ONCE(最后在try块之后执行块),并在循环内部执行ONCE。因此,如果代码以某种方式使其通过finally块中的writer.close(),它将永远不会使它通过循环多次。

没有必要关闭BufferedWriter。该课程确保在内部关闭它。

答案 2 :(得分:0)

如果您使用的是Java 7,则可能需要考虑使用"try-with-resources"语法,这样可以在这种情况下大大简化文件处理的正确实现。您的原始代码存在一些问题,但即使是已接受的答案也存在一些问题,我认为在无法打开文件(未验证)的情况下会导致NullPointerException

我认为你的while循环边界条件也可能有些问题。我已将while循环更改为更传统的for循环。请记住,java数组元素从0array.length - 1包含。

  public static void stuIDWrite() throws IOException
  {
    try (FileWriter writer = new FileWriter("Res/stuIDSorted.txt"))
    {
      for (int i = 0; i < stuArrayIdSort.length; ++i)
      {
        ln = stuArrayIdSort[i].getStuLastName();
        fn = stuArrayIdSort[i].getStuFirstName();
        pn = stuArrayIdSort[i].getStuFirstName();
        id = stuArrayIdSort[i].getStuId();
        ft = stuArrayIdSort[i].getFTime();
        phn = stuArrayIdSort[i].getPhoneNum();
        lj = stuArrayIdSort[i].getLovJava();
        con = stuArrayIdSort[i].getCont();
        writer.write(ln + "," + fn + "," + pn + "," + id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
      }
    }
  }

您还可以使用内部循环的"enhanced for loop"语法来进一步简化操作。