简体   繁体   English

Java Inventory - 如何使用FileInputStream读取文件?

[英]Java Inventory - How to read a file using FileInputStream?

For one of my last assignments this semester, I had to create an inventory program that contained an array of Item objects. 对于本学期的最后一次作业,我必须创建一个包含Item对象数组的库存程序。 Each Item contains an ID (that is assigned when you add an item and CANNOT be modified), name, description, number of items on hand, and the unit price. 每个项目都包含一个ID(在添加项目时无法修改时分配),名称,描述,库存项目数量和单价。

I also need to save and load files using File I/O Stream. 我还需要使用File I / O Stream保存和加载文件。 I am able to save to a text file just fine. 我能够保存到文本文件就好了。 However, I am having trouble getting started on my readFile method. 但是,我无法开始使用readFile方法。 I was really trying to get through this assignment without asking for any help, but I am stumped. 我真的试图通过这项任务而不寻求任何帮助,但我很难过。 How would I read in text files using FileInputStream? 我如何使用FileInputStream读取文本文件?

Item Class 物品等级

import java.text.NumberFormat;

public class Item
{
    private int ID;
    private String name;
    private String Desc;
    private int onHand;
    private double unitPrice;

    public Item(int pID)
    {
        ID = pID;
    }

    public Item(int pID, String pName, String pDesc, int pOnHand, Double pUnitPrice)
    {
        ID = pID;
        name = pName;
        Desc = pDesc;
        onHand = pOnHand;
        unitPrice = pUnitPrice;
    }

    public void display()
    {
        NumberFormat dollars = NumberFormat.getCurrencyInstance();
        System.out.printf("%-6s%-20s%-24s%-12s%-6s\n", ID, name, Desc, onHand, dollars.format(unitPrice));
    }

    // GETTERS AND SETTERS
    public int getID()
    {
        return ID;
    }

    public void setName(String pName)
    {
        name = pName;
    }

    public String getName()
    {
        return name;
    }

    public void setDesc(String pDesc)
    {
        Desc = pDesc;
    }

    public String getDesc()
    {
        return Desc;
    }

    public void setOnHand(int pOnHand)
    {
        onHand = pOnHand;
    }

    public int getOnHand()
    {
        return onHand;
    }
    public void setUnitPrice(double pUnitPrice)
    {
        unitPrice = pUnitPrice;
    }

    public double getUnitPrice()
    {
        return unitPrice;
    }

}

Inventory Class 库存类

import java.util.Scanner;
import java.io.PrintWriter;
import java.io. FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Inventory
{
    int max = 30;
    int count = 0;
    Item myItem[] = new Item[max];
    Scanner scannerObject = new Scanner(System.in);

    public void addItem()
    {
        try{
            if (count >= max)
            {
                System.out.println("\nNo more room!");
            }else{
                System.out.print("\nPlease enter name of item: ");
                String lname = scannerObject.nextLine();
                System.out.print("\nPlease enter a brief description of the item: ");
                String ldesc = scannerObject.nextLine();
                System.out.print("\nPlease enter the amount on hand: ");
                int lonHand = scannerObject.nextInt();
                System.out.print("\nPlease enter unit price of the item: $");
                Double lunitPrice = scannerObject.nextDouble();
                myItem[count] = new Item(count + 1, lname, ldesc, lonHand, lunitPrice);
                count++;
                System.out.println("\nThank you. The ID number for " + lname + " is " + count);
                scannerObject.nextLine();
            }
        }catch(Exception e)
        {
            System.out.println("\nERROR! Please try again:\n");
            scannerObject.nextLine();
        }

    }

    public int findItem()
    {
        int found = -1;
        int inputID =0;
        try{
            System.out.print("\nGreetings, please enter the ID number for item:\n");
            inputID = scannerObject.nextInt();
            for(int i = 0; i < count; i++){
                if(myItem[i].getID() == inputID){
                    found = i;
                    scannerObject.nextLine();
                }
            }
        }catch(Exception e)
        {
            System.out.println("\nERROR!");
            scannerObject.nextLine();
        }
        return found;
    }

    public void modify()
    {
        int lfound = findItem();
        if (lfound == -1){
            System.out.println("\nInvalid input! Please try again:");
            scannerObject.nextLine();
        }else{
            try{
                System.out.print("\nPlease enter name of item: ");
                String lname = scannerObject.nextLine();
                myItem[lfound].setName(lname);
                System.out.print("\nPlease enter a brief description of the item: ");
                String ldesc = scannerObject.nextLine();
                myItem[lfound].setDesc(ldesc);
                System.out.print("\nPlease enter the amount on hand: ");
                int lonHand = scannerObject.nextInt();
                myItem[lfound].setOnHand(lonHand);
                System.out.print("\nPlease enter unit price of the item: $");
                double lunitPrice = scannerObject.nextDouble();
                myItem[lfound].setUnitPrice(lunitPrice);
                scannerObject.nextLine();
            }catch (Exception e)
            {
                System.out.println("\nInvalid command! Please try again: ");
                scannerObject.nextLine();
            }
        }
    }

    public void displayAll()
    {   System.out.println("_______________________________________________________________________________\n");
        System.out.println("                                 Inventory                                     ");
        System.out.println("_______________________________________________________________________________\n");
        System.out.printf("\n%-6s%-20s%-24s%-12s%-6s\n", "ID:", "Name:", "Description:","On Hand:", "Unit Price:\n"); //Header
        System.out.println("_______________________________________________________________________________\n");
        for(int i = 0; i < count; i++){
            myItem[i].display();
        }
    }

    public void displayOne()
    {
        int lfound = findItem();
        if (lfound == -1){
            System.out.println("\nInvalid input! Please try again:");
        }else{
            System.out.println("_______________________________________________________________________________\n");
            System.out.println("                                 Inventory                                     ");
            System.out.println("_______________________________________________________________________________\n");
            System.out.printf("\n%-6s%-20s%-24s%-12s%-6s\n", "ID:", "Name:", "Description:","On Hand:", "Unit Price:\n"); //Header
            System.out.println("_______________________________________________________________________________\n");
            myItem[lfound].display();
        }
    }

    public void saveFile()
    {
        PrintWriter outputStream = null;
        try{
            outputStream =
                new PrintWriter(new FileOutputStream("H:\\Java\\saveFile.txt"));
        }catch (FileNotFoundException e)
        {
            System.out.println("Error!");

        }
        if(outputStream != null)
            for(int i = 0; i < count; i++){
                outputStream.println(myItem[i].getID());
                outputStream.println(myItem[i].getOnHand());
                outputStream.println(myItem[i].getUnitPrice());
                outputStream.println(myItem[i].getName());
                outputStream.println(myItem[i].getDesc());
            }
        outputStream.close();
    }
}

User Class 用户类

import java.util.Scanner;

public class inventUser
{

    public static void main(String[] args)
    {
        Inventory myInvent = new Inventory();
        Scanner scannerObject = new Scanner(System.in);
        int Choice = 0;

        do{

            dispMenu();

            Choice = getChoice(scannerObject);

            proChoice(Choice, myInvent);

        }while (Choice !=0);
    }

    public static void dispMenu()
    {
        System.out.println("\n|=============================================|");
        System.out.println("|                                             |");
        System.out.println("|******************Welcome********************|");
        System.out.println("|_____________________________________________|");
        System.out.println("|                                             |");
        System.out.println("|       Press [1] To Add An Item              |");
        System.out.println("|                                             |");
        System.out.println("|       Press [2] To Display One Item         |");
        System.out.println("|                                             |");
        System.out.println("|       Press [3] To Display All Items        |");
        System.out.println("|                                             |");
        System.out.println("|       Press [4] To Modify An Item           |");
        System.out.println("|                                             |");
        System.out.println("|       Press [0] To Exit                     |");
        System.out.println("|_____________________________________________|");
        System.out.println("|=============================================|");
        System.out.println("|         Please Make Selection Now...        |");
        System.out.println("|=============================================|");
        System.out.println("|_____________________________________________|\n");
    }

    public static int getChoice(Scanner scannerObject)
    {
        boolean x = false;
        int pChoice = 0;
        do{
            try{
                pChoice = scannerObject.nextInt();
                x = true;
            }catch (Exception e){
                scannerObject.next();
                System.out.println("\nInvalid command! Please try again:\n");
            }
        }while (x == false);
        return pChoice;
    }

    public static void proChoice(int Choice, Inventory myInvent)
    {
        switch(Choice){
            case 1: myInvent.addItem();
                break;
            case 2: myInvent.displayOne();
                break;
            case 3: myInvent.displayAll();
                break;
            case 4: myInvent.modify();
                break;
            case 0: System.out.println("\nHave a nice day!");
                break;
        }myInvent.saveFile();
    }
}

Per my instructor, I need to have my save and read file methods in my inventory class. 根据我的讲师,我需要在库存类中保存和读取文件方法。 I need to invoke them in my user class. 我需要在我的用户类中调用它们。 While I have a "getter" for my Item ID variable, I am not allowed to use a "setter". 虽然我的Item ID变量有“getter”,但我不允许使用“setter”。

I am still fairly new to Java, so please excuse any rookie mistakes. 我还是Java的新手,所以请原谅任何新手的错误。 Again, any help is greatly appreciated! 再次,非常感谢任何帮助! I looked in my book and Googled for examples but I could not find anything relevant to my situation. 我查看了我的书和谷歌搜索的例子,但我找不到任何与我的情况相关的东西。

To read a file using FileInputStream simply use: 要使用FileInputStream读取文件,只需使用:

Scanner input = new Scanner(new FileInputStream("path_to_file"));

Use methods of Scanner to read 使用扫描仪的方法来阅读

while(input.hasNextLine()) { //or hasNextInt() or whatever you need to extract
  input.nextLine() //... read in a line of text from the file
}

You can also use the File class if you wish to perform any File manipulations using File class methods 如果要使用File类方法执行任何文件操作,也可以使用File类

File myTextFile = new File("path_to_file");
Scanner input = new Scanner(new FileInputStream(myTextFile));

You need to of course catch the FileNotFoundException 您当然需要捕获FileNotFoundException

Otherwise, it's really the same as you've been doing for PrintWriter. 否则,它与您为PrintWriter所做的一样。 Just switch FileOutputStream for FileInputStream , and PrintWriter for Scanner , but do not forget to first close the file when switching from writing or reading from the file: 只需为FileInputStream切换FileOutputStream ,为Scanner切换PrintWriter ,但不要忘记在从写入或从文件读取切换时先关闭文件:

input.close() // or output.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM