如何从链接列表中的文件和存储数据中读取

时间:2017-02-28 00:38:26

标签: java file-io linked-list

我正在尝试从文件中读取并将数据存储到单个链接列表中。

数据应包含有关用户的信息,其中包括id类型longname类型string和类型threat level int }。此外,我想知道如何从文件中读取并存储到链表中,以便我可以执行多个操作。

我的尝试:

课程POI

public class POI {

    private long id;
    private String name; 
    private int level;

    public POI(){

    }

    public POI(long n, String s, int l){
        id = n;
        name = s;
        level = l;
    }

    public void setID (long n){
        id = n;
    }

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

    public void setLevel (int l){
        level = l;
    }

    public long getID(){
        return id;
    }

    public String getName(){
        return name;
    }

    public int getLevel(){
        return level;
    }
}

class POIList

public class POIList {
    static private class Node {
        int data;
        Node next;
        Node () {
            data = 0;
            next = null;
        }
        Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }
    } 

    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data + ", ");
            head = head.next;
        }
        System.out.println();
    }

    public Node insertNode(Node head, Node insertee, int position) {
        if (position < 0) {
            System.out.println("Invalid position given");
            return head;
        }
        if (head == null) {
            return insertee;
        }
        if (position == 0) {
            insertee.next = head;
            return insertee;
        }
        int i = 0;
        Node current=head;        
        while (i < position - 1 && current.next != null) {
            current = current.next;
            i++;
        }
        if (i == position - 1) {
            insertee.next = current.next;
            current.next = insertee;
        } else {
            System.out.println("Position was not found.");
        }
        return head;
    }

    static Node swapNode(Node head,
            int position1, int position2) {
        if(position1 < 0 || position2 < 0)
            System.out.println("InvalidPos");
        Node n1 = null;
        Node n2 = null;
        Node prev1=null;
        Node prev2=null;
        int maxPosition = Math.max(position1, position2);
        if (position1==maxPosition){
            position1=position2;
            position2=maxPosition;
        }
        Node temp=head;
        for (int i = 0;i <= maxPosition; i++) {
            if (temp == null) {
                System.out.println("InvalidPos");
                return head;
            }
            if (i==position1-1) prev1=temp;
            if(i == position1) n1 = temp;
            if (i==position2-1) prev2=temp;
            if(i == position2) n2 = temp;
            temp = temp.next;
        }
        temp = n2.next;
        if (prev1!=null){
            prev1.next=n2;
        }else{
            head=n2;
        }
        if (position2-position1==1){
            n2.next=n1;
        }else{
            n2.next=n1.next;
        }
        if (prev2!=null){
            prev2.next=n1;
        }else{
            head=n1;
        }
        n1.next=temp;
        return head;
    } // End of swapNode

    public static Node removeNode(Node head, int position) {
        if (position < 0 || head == null) {
            System.out.println("Invalid position given");
            return head;
        }
        if (position == 0) {
            return head.next;
        }
        int i = 0;
        Node current = head;
        while (i < position - 1 && current.next != null) {
            current = current.next;
            i++;
        }
        if (current.next != null) {
            current.next = current.next.next;
        } else {
            System.out.println("Position was not found.");
        }
        return head;
    }
}

class AnalyzePOI

public class AnalyzePOI {

    public static void main (String [] args) throws FileNotFoundException, IOException{
        Scanner scan = new Scanner(System.in);
        int choice;

        System.out.print("Input filename:");
        String filename = scan.nextLine();
        File file = new File(filename);
        Scanner reader = new Scanner(file);

        POIList list = new POIList();
        System.out.println("What operation would you like to implement? ");
        choice = scan.nextInt();

        switch (choice) {
        case 1 : print(list) ; 
            break ;
        case 2 : search(reader, list) ;
            break ;
        case 3 :  insert(scan, list);
            break ;
        case 4 : swap(reader, list);
            break ;
        case 5 : remove1(reader, list);
            break;
        case 6 : remove2(reader, list);
            break; 
        case 7 : output();
            break;
        case 8 :
            System.out.println ("Program Terminated");
            System.exit(0);
            break;
        }

        start(scan,file, reader );
    }

    public static void start (Scanner scan, File file, Scanner reader){
        String content = new String();
        int count=1;
        File file1 = new File("abc.txt");
        LinkedList<String> list = new LinkedList<String>();

        try {
            Scanner sc = new Scanner(new FileInputStream(file));
            while (sc.hasNextLine()){
                content = sc.nextLine();
                list.add(content);
            }
            sc.close();
        }catch(FileNotFoundException fnf){
            fnf.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("\nProgram terminated Safely...");
        }

        Collections.reverse(list);
        Iterator i = (Iterator) list.iterator();
        while (((java.util.Iterator<String>) i).hasNext()) {
            System.out.print("Node " + (count++) + " : ");
            System.out.println();
        }
    }

    public static void print(POIList list) {
        list.print(null);
    }

    public static void search(Scanner scan, POIList list) {
        int id;
        String name;

        System.out.println("Do you want to enter id or name to search for record: ");
        String answer = scan.next();
        if (answer == "id"){
            System.out.println ("Enter the id to find the record: ");
            id = scan.nextInt();
        }
        else if (answer == "name"){
            System.out.println("Enter the name to find the record: ");
            name = scan.nextLine();
        }
        else{
            System.out.println("Invalid input");
        }
    }

    public static void insert(Scanner scan, POIList list) {
        System.out.println("Enter the the location index ");
        int index = 0; 
        long p1;
        int level;
        String name;

        try {
            System.out.println("Index: ") ; 
            index= scan.nextInt() ; 
            System.out.println("ID: ") ;
            p1=scan.nextLong() ;
            System.out.println("Name: ");
            name = scan.nextLine();
            System.out.println("Threat Level ") ; 
            level=scan.nextInt() ;
        }

        catch (InputMismatchException e) {
            System.out.print("Invalid Input") ;
        }
        list.insertNode(null, null, index);
    }

    public static void swap(Scanner scan, POIList list) {
        System.out.println("Enter index 1 to swap record: ");
        int index1 = scan.nextInt();
        System.out.println("Enter index 2 to swap record: ");
        int index2 = scan.nextInt();
        list.swapNode(null, index1, index2);    
    }

    public static void remove1(Scanner scan, POIList list) {
        int index= 0;
        try{ 
            System.out.println("Enter ID to remove a record: ") ;
            index=scan.nextInt() ;
        }
        catch (InputMismatchException e) {
            System.out.print("Invalid Input") ;
        }

        list.removeNode(null, index) ;
    }

    public static void remove2(Scanner scan, POIList list){
        int index = 0;
        try{
            System.out.println("Enter threat level to remove a record: ");
            index=scan.nextInt() ;
        }
        catch (InputMismatchException e){
            System.out.println("Invalid Input");
        }
        list.removeNode(null, index) ;
    }
    public static void output() {

    }
}

1 个答案:

答案 0 :(得分:0)

假设您的问题,您想知道如何读取包含“String”“long”和“int”值的文件。假设您的输入文件如下所示:

首先,我们需要了解数据的外观。我假设I / P看起来像这样

{
 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "lib": ["es6", "dom"],
    "types":[
    ],
    "typeRoots": [
        "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "node_modules/protractor/node_modules"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "!./node_modules/**/*.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true,
    "compiler": "node_modules/typescript"
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}

现在,我假设的顺序是“long”“String”“int”,每行之间有一个空格。使用bufferedReader可以更快地阅读。

1 OneString 10
2 TwoSTring 20

addPOI方法看起来像这样。

FileReader fr = new FileReader("yourFile.txt");
BufferedReader br = new BufferedReader(fr);
String curLine = br.next();
while(curLine!=null)
{
String[] tempLine = curLine.split(" ");
int threat = Integer.parseInt(tempLine[0]);
String user = tempLine[1];
long ID = Long.parseLong(tempLine[2]);
addPOI(ID,user,threat);
}

列表可以声明为这样,

public void addPOI(long ID, String user, int threatLevel)
{
list.addAtLast(new POI(ID,user,threadLevel));
}