-1

I need to read data from two .txt files and then sort its data as a queue or a stack. I know how to use queue and stacks but my problem is how I can open and use the data from the txt files.

Example

File1.txt = A B C

File2.txt = D E F

--Stack= C B A F E D
--Queue= A B C D E F

2 Answers2

0

There are multiple ways to read a file into a variable.

One way would be by making use of the Scanner class to read the content of a file line by line. Here is a small code example reading a file from the filesystem, and printing the content, line by line. You can use this and instead of printing the content, append it in your queue and stack.

try {
    File file1= new File("File1.txt");
    Scanner fileReader= new Scanner(file1);
    
    while (fileReader.hasNextLine()) {
        String fileLine= fileReader.nextLine();
        System.out.println(fileLine);
    }
    
    fileReader.close();
} catch (FileNotFoundException e) {
    System.out.println("File could not be found.");
}
Yoni
  • 1,370
  • 7
  • 17
0

Use BufferedReader

File file=new File("file1.txt");
BufferedReader  reader=new BufferedReader(new FileReader(file));
String line="";
while((line=reader.readLine())!=null){
     // enqueue(line);
     //  push(line);
}

Do this for the Two files

  • I'm trying to use this, but it says : "Incompatible types: File cannot be converted to reader" – Diego Samayoa Feb 24 '21 at 19:58
  • Use This ,or the edited one File file=new File("file1.txt"); BufferedReader reader=new BufferedReader(new FileReader(file)); String line=""; while((line=reader.readLine())!=null){ // enqueue(line); // push(line); } – Takele Arega Feb 24 '21 at 20:48