簡體   English   中英

無法在Java中寫入文件

[英]Trouble Writing to file in java

嘿,我試圖寫入文件,但是在寫入文本文件每一行的那一行上卻出現錯誤,無法找出任何幫助,將非常感謝The Writer Code。

 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,

好的,這是您應該做的:

發生的事情是您在實際上無法執行任何操作之前將其關閉。 因此,讓您將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) {}
 }

我不確定您是否了解try ... catch ...最終的工作方式。 這是您所擁有的:

     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。 該類確保在內部將其關閉。

如果您使用的是Java 7,則可能要考慮使用“ try-with-resources”語法,在這種情況下,它可以大大簡化文件處理的正確實現。 您的原始代碼有一些問題,但是即使無法接受,也有一些問題,我相信在無法打開文件(未經驗證)的情況下,會導致NullPointerException

我認為您的while循環邊界條件也可能有一些問題。 我將while循環更改為更傳統的for循環。 請記住,Java數組元素的范圍是0array.length - 1包括array.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");
      }
    }
  }

您還可以考慮對內部循環使用“增強的循環”語法,這可能會進一步簡化事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM