使用java修改txt文件中的整行数据

时间:2017-05-10 08:26:31

标签: java oop text netbeans console

所以我有一个带有Java代码的控制台应用程序,用于修改txt文件中的Book数据。 系统将提示用户输入要修改的图书的书籍ID,然后基本输入所有图书详细信息。

public void UpdatingBookData()
    {
        int bid; String booktitle; String author; String desc; String Alley;
        System.out.println("Enter Book ID: ");
        bid = sc.nextInt();
        System.out.println("Enter Book Title: ");
        booktitle = sc.next();
        System.out.println("Enter Book Author: ");
        author = sc.next();
        System.out.println("Enter Book Description: ");
        desc = sc.next();
        System.out.println("Enter Book Alley: ");
        Alley = sc.next();

        UpdateBook(bid, booktitle, author, desc, Alley);
    }

    public static void UpdateBook(int bid, String booktitle, String author, String desc, String Alley)
    {
        ArrayList<String> TempArr = new ArrayList<>();
        try
        {
            File f = new File("book.txt");
            FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            String line;
            String[] lineArr;
            line = br.readLine();
            while(line != null)
            {
                lineArr = line.split(" ");
                if(lineArr[0].equals(bid))
                {
                    TempArr.add(

                             bid + " " +
                             booktitle + " " +
                             author + " " +
                             desc + " " +
                             Alley );
                }
                else
                {
                    TempArr.add(line);
                }
            }
            fr.close();
        }
        catch(IOException ex)
        {
            System.out.println(ex);
        }

        try
        {
           FileWriter fw = new FileWriter("book.txt");
           PrintWriter pw = new PrintWriter(fw);

           for(String str : TempArr)
           {
               pw.println(str);
           }
           pw.close();
        }
        catch(IOException ex)
        {
            System.out.println(ex);
        }

    }

但是当我运行它时,我一直收到此错误

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at lmsconsole.Administrator.UpdateBook(Administrator.java:438)
    at lmsconsole.Administrator.UpdatingBookData(Administrator.java:409)
    at lmsconsole.Administrator.adminPanel(Administrator.java:52)
    at lmsconsole.MainMenu.loginAdmin(MainMenu.java:68)
    at lmsconsole.MainMenu.MainPanel(MainMenu.java:45)
    at lmsconsole.LMSConsole.main(LMSConsole.java:24) 

是因为ArrayList还是什么?提前谢谢!

0 个答案:

没有答案