Java - 将文件读入数组

Posted

技术标签:

【中文标题】Java - 将文件读入数组【英文标题】:Java - Reading files into array 【发布时间】:2015-01-10 03:13:01 【问题描述】:

我想为存储技术手册的小型 Java 应用程序保存一个库。现在我可以将库保存到外部文件,但我无法将其加载回库本身,目前“-1”只是打印到控制台。

我该如何解决这个问题?

这是我的代码:

            //Choice 7: Load Library:

            if(Menu.menuChoice == 7)
                boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
                String fileName = "Library.bin";
                if(loadYesNo==true)
                    try 
                        FileInputStream fileIs = new FileInputStream(fileName);
                        ObjectInputStream is = new ObjectInputStream(fileIs);
                        int x = is.read();
                        System.out.println(x);
                        is.close();
                     catch (FileNotFoundException e) 
                        e.printStackTrace();
                     catch (IOException e) 
                        e.printStackTrace();
                    
                    Menu.displayMenu();
                
                else if(loadYesNo==false)
                    System.out.println("\n\n--------------------------------------------------------------------------");
                    System.out.println("\n                             Library not loaded!\n");
                    System.out.println("--------------------------------------------------------------------------\n");
                    Menu.displayMenu();
                
            


            //Choice 0: Exit the program:

            if(Menu.menuChoice == 0)
                if(Menu.menuChoice == 0)
                    if(Library.ManualList.size() > 0)
                        boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
                        String fileName = "Library.bin";
                        if(saveYesNo==true)
                            try 
                                FileOutputStream fileOs = new FileOutputStream(fileName);
                                ObjectOutputStream os = new ObjectOutputStream(fileOs);
                                for (int i = 0; i < Library.ManualList.size(); i++)
                                    os.writeObject(Library.ManualList.get(i).displayManual());
                                    os.close();
                                
                             catch (FileNotFoundException e) 
                                e.printStackTrace();
                             catch (IOException e) 
                                e.printStackTrace();
                            
                            System.out.println("DONE WRITING!");

                         else if(saveYesNo==false)
                            System.out.println("\n\n--------------------------------------------------------------------------");
                            System.out.println("\n                              Library not saved!\n");
                            System.out.println("--------------------------------------------------------------------------\n");
                            break exit;
                        
                        Menu.displayMenu();
                    else if(Library.ManualList.isEmpty()) 
                        Menu.displayMenu();
                    
                
                           

        
        System.out.println("\n              ~   You have exited the manualKeeper app!   ~                  ");
        System.out.println("\n                  Developed by Oscar Moore - 2014 - UWL\n");
        System.out.println("\n                                   <3\n");

    

这也是我的库类:

package library;

import java.util.ArrayList;

public class Library   

    public static int ManualChoice;

    static String returnManualTitle;

    static String status1 = "Available";

    static String status2 = "Borrowed"; 

    public static ArrayList<Manual> ManualList = new ArrayList<Manual>();
    static ArrayList<Manual> borrowedManuals = new ArrayList<Manual>();

    static void addManual()
        Manual newManual = new Manual(); 
        newManual.createManual();
        ManualList.add(newManual);
        System.out.println("\n\n--------------------------------------------------------------------------");
        System.out.println("\n                          Manual added to library!\n");
        System.out.println("--------------------------------------------------------------------------\n");
    

    static void displayManualList()
        if (ManualList.isEmpty())
            System.out.println("-------------------------------------------------------------");
            System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
            System.out.println("-------------------------------------------------------------");
            Menu.menuChoice = 8;

         else     
            System.out.printf("\n\nHere are the Manual/s currently stored in the library:\n\n\n");
            for (int i = 0; i < ManualList.size(); i++)
                System.out.printf("-------------------- Index Number: %s --------------------\n",i);
                System.out.println(ManualList.get(i).displayManual());  
                System.out.println("---------------------------------------------------------\n");
            
        
    

    static void displayBorrowedManuals()
        if (ManualList.isEmpty())
            System.out.println("-------------------------------------------------------------");
            System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
            System.out.println("-------------------------------------------------------------");
            Menu.menuChoice = 8;

         else                     
            for (int i = 0; i < borrowedManuals.size(); i++)
                System.out.printf("-------------------- Index Number: %s --------------------\n",i);
                System.out.println(borrowedManuals.get(i).displayManual()); 
                System.out.println("---------------------------------------------------------");
            
        
    

    public static void borrowManual()

        displayManualList();
        ManualChoice = (Console.readInteger(Messages.enterManualIndexMessage, Messages.ManualIndexNotInListMessage, 0, Library.ManualList.size() - 1));

        borrowLoop:
        while(Menu.menuChoice == 3)

            if ((ManualList.get(ManualChoice).status.equalsIgnoreCase(status1)) && (ManualList.size() >= ManualChoice))
                ManualList.get(ManualChoice).status = "Borrowed";
                ManualList.get(ManualChoice).borrower = User.userName;
                ManualList.get(ManualChoice).borrowDate = "Today.";
                ManualList.get(ManualChoice).returnDate = "In two weeks.";
                borrowedManuals.add(ManualList.get(ManualChoice));
                System.out.println("\n--------------------------------------------------------------------------");
                System.out.println("\n                             Manual borrowed!\n");
                System.out.println("--------------------------------------------------------------------------\n");
                break borrowLoop;

            else if(ManualList.get(ManualChoice).status.equalsIgnoreCase(status2) && ManualList.size() >= ManualChoice)
                System.out.println("\n--------------------------------------------------------------------------");
                System.out.println("\n            "
                        + " The Manual you wish to borrow is already on loan.");
                System.out.println("\n--------------------------------------------------------------------------\n");
                break borrowLoop;

            else if(ManualChoice > ManualList.size()-1)
                System.out.println(Messages.noSuchManualMessage);
                break borrowLoop;
            
            if(ManualList.size() > 1)
                displayManualList();
            
            else if(ManualList.size() == 1)
                ManualList.get(ManualChoice).status = "Borrowed";
                ManualList.get(ManualChoice).borrower = User.userName;
                ManualList.get(ManualChoice).borrowDate = "Today.";
                ManualList.get(ManualChoice).returnDate = "In two weeks.";
                borrowedManuals.add(ManualList.get(ManualChoice));
                System.out.printf("\n\n %s\n\n", ManualList.get(ManualChoice).displayManual());
                System.out.println("Please return the Manual within two weeks!\n");
                displayManualList();
            
        
        Menu.displayMenu();
    

    static void returnManual()
        System.out.printf("\n\nHere are the Manual/s currently out on loan:\n\n");

        if(borrowedManuals.size() > 0)
            for (int i = 0; i < borrowedManuals.size(); i++)
                System.out.println(borrowedManuals.get(i).displayManual());
            returnManualTitle = Console.readString(Messages.enterManualSerial, Messages.tooShortMessage, 3);
        

        int x = 0;
        boolean serialExistance = false;
        while (x < ManualList.size())

            if (ManualList.get(x).serial.equalsIgnoreCase(returnManualTitle))

                ManualList.get(x).status = "Available";
                ManualList.get(x).borrower = "N/A";
                ManualList.get(x).borrowDate = "N/A";
                ManualList.get(x).returnDate = "N/A";

                int p = 0;
                while (p < borrowedManuals.size()) 
                    Manual borrowed = borrowedManuals.get(p);
                    if (borrowed.serial.equalsIgnoreCase(returnManualTitle)) 
                        borrowedManuals.remove(p);
                        break;
                    
                    p++;
                               
                System.out.println(Messages.successReturnMessage);
                serialExistance = true;

                break;
            
            x = x+1;
        
        if(serialExistance == false)
            boolean repeatReturnManual = Console.readYesNo("\n--------------------------------------------------------------------------" + "\n\nThe Manual with the serial "+"\""+returnManualTitle +"\""+ " wasn't found!"
                                                            +"\n\nDo you want to try again? (Y/N):\n");
            System.out.println("\n--------------------------------------------------------------------------");
            if(repeatReturnManual)
                returnManual();
            
        else if(serialExistance)
            Menu.menuChoice = 8;
                       
    

    public static void removeManual()

        if(ManualList.size() >0)
            displayManualList();
            ManualChoice = Console.readInteger(Messages.enterRemoveManualIndex ,Messages.ManualIndexNotInListMessage, 0, ManualList.size());        
            int p = 0;
            while (p < borrowedManuals.size())

                if (borrowedManuals.get(p).title.equalsIgnoreCase(returnManualTitle))

                    borrowedManuals.remove(p);
                
            
            ManualList.remove(ManualChoice);
            System.out.print(Messages.successRemovedManualMessages);
            Menu.menuChoice = 8;
                       
    

    static void emptyLibrary()
        System.out.println("\n                                 WARNING!");
        System.out.println("\n           You have chosen to delete all Manuals in the library.\n"); 
        System.out.println("--------------------------------------------------------------------------");
        boolean emptyLibraryChoice = Console.readYesNo("\nAre you sure you wish to destroy the library? (Y/N): \n");
        System.out.println("\n--------------------------------------------------------------------------\n");
        if(emptyLibraryChoice)
            Library.ManualList.clear();
            System.out.println(Messages.successEmptyLibraryMesssage);
            System.out.println("--------------------------------------------------------------------------\n");
            Menu.menuChoice = 8;
        

    


【问题讨论】:

【参考方案1】:

您未按预期方式使用ObjectInputStream。正确的方法是:

ObjectInputStream is = new ObjectInputStream(fileIs);
Library x = (Library) is.readObject();  // change Library to the type of object you are reading
System.out.println(x);

您可能需要更改库,但我不知道您正在阅读什么类型的对象。

【讨论】:

以上是关于Java - 将文件读入数组的主要内容,如果未能解决你的问题,请参考以下文章

C++ 图像处理 - 将图像文件读入二维数组

Java - 如何将用空格分隔的整数读入数组

在Java中将文件读入字节[]数组的优雅方法[重复]

将文件列读入数组

node.js:将文本文件读入数组。 (每一行都是数组中的一个项目。)

如何将文件中的特定数据读入数组字符串