JAVA Попытка использовать QueueFileList Как? - PullRequest
0 голосов
/ 18 октября 2018

Здравствуйте, мне нужен для моего проекта список FIFO.Когда довольно просто, я думаю.Если я загружу несколько из них, они должны войти в списокЕсли файл успешно загружен, он будет удален, и следующий может идти.после этого мне нужно положить его в JTable введите описание изображения здесь

class QueueList {

    public static void main(String args[]) {

        BuildServerServerApplicationTests bq = new BuildServerServerApplicationTests();
        char[] arr = bq.filename;
        Queue<String> fifo = new LinkedList<String>();

        for (int i = 0; i < arr.length; i++)
            fifo.add (String.valueOf(new Integer (arr[i])));

        System.out.print (fifo.remove() + ".");
        while (! fifo.isEmpty())
            System.out.print (fifo.remove());
        System.out.println();
    }
}

Это то, что у меня есть, но почему-то мне не хватает чего-то, надеюсь, вы можете помочь Thx

1 Ответ

0 голосов
/ 18 октября 2018

это было трудно понять , в чем именно заключалась проблема и что вы пытались сделать, поэтому я немного импровизировал, но это должно помочь вашему проекту немного продвинуться.

Взятьобратите внимание на мои комментарии при реализации, как загрузить ваши файлы.

"после этого мне нужно поместить его в JTable" - я оставил это для вас, чтобы сделать,Я снова предположил, что вы будете загружать содержимое текстового файла в JTable.Поэтому вместо того, чтобы печатать содержимое, как я сделал, вам придется анализировать каждую строку текста, которая находится в arrayContents, и затем соответствующим образом вставлять ее в ваши объекты JTable.

Удачи.Студент23

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Fifo {

public static void main (String [] args) {

    // Your code says fifo.add (String.valueOf(new Integer (arr[i]))); 
    // I Assume arr is a char array of numbers resembling file names
    Character[] arr = {'1', '2', '3', '0'};

    System.out.println("Populating FIFO queue...\n");

    List<String> fifo = Stream.of(arr)      // create a stream from arr
            .map(String::valueOf)           // map each element to a String
            .collect(Collectors.toList());  // collect results

    System.out.println("FIFO queue  > " + fifo.toString());

    readAndAddToJTable(fifo);

    System.out.println("\nIs fifo empty? FIFO queue > " + fifo.toString());

    System.out.println("\nDone.");

}

// Read the file in the FIFO queue and add to JTable
private static void readAndAddToJTable(List<String> fifoQueue) {

    System.out.println("\nProcessing FIFO queue...\n");

    while(!fifoQueue.isEmpty()) {

        String fileName = fifoQueue.remove(0); // Remove and return first element in fifo queue

        /*
         * 1) Load the file and do something with it.
         *      --- Note that you should rather use getResource() or getResourceAsStream()
         *          as its safer, but I am lazy. Using absolute paths can break your program
         *          if the directory structure were to change. You can find these methods
         *          in the Class class.
         * 
         * 2) Read the contents of each file and do something with its contents.
         *      --- I just print its contents out...
         *      --- You want read the contents and add it to your JTable. You will have
         *          to parse the file contents e.g. splitting the strings, etc.
         */

        File file = new File("C:\\Users\\Mathew\\StackOverflow\\src\\" + fileName); // dangerous!

        ArrayList<String> fileContents = readFileToArrayList(file); // store the text in my tester files

        if (fileContents != null) {

            // Do something with the contents (I print each line out, you add to JTable)
            for(int i = 0; i < fileContents.size(); i ++) { 
                System.out.println("Contents of file " + file.getName() + " > " + fileContents.get(i));
            }

        } else {
            System.out.println("fileContents array = null");
        }
    }
}

// Read text file contents into an ArrayList and return the ArrayList.
// This can probably be done with a Stream() as well, but I cant remember how.
private static ArrayList<String> readFileToArrayList(File f) {

    ArrayList <String> content = new ArrayList <String> ();
    try {
        Scanner scanner = new Scanner(f);
        while(scanner.hasNextLine() == true) {
            content.add(scanner.nextLine()); // Add to end of the list
        }
        scanner.close();
    } catch(Exception e) {
        e.printStackTrace();;
        content = null;
    }
    return content;
}

}

...