Open the text file and read each line as a String and place that String object into a LinkedList. Print all of the lines in the LinkedList in reverse order.

import java.util.*;
import java.io.*;

public class FileLinkList
{
public static void main(String args[])throws IOException{
String content = new String();
int count=1;
File file = 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 = list.iterator();
while (i.hasNext()) {
System.out.print("Node " + (count++) + " : ");
System.out.println(i.next());
}
 }
 }
Answer from Mavrick on Stack Overflow
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 454055 › creating-a-linked-list-from-the-contents-of-a-file
Creating a Linked List from the contents of a file - java
A straightforward approach is to build the list directly as you read. No need to first concatenate the entire file into one giant String, which only wastes memory. import java.io.File; import java.io.FileNotFoundException; import java.util....
🌐
Reddit
reddit.com › r/javahelp › [project help] reading from a text-file, and putting it into a linked list. need someone to point me in the right direction.
r/javahelp on Reddit: [Project Help] Reading from a text-file, and putting it into a linked list. Need someone to point me in the right direction.
November 16, 2014 -

I was wondering if someone could point me in the right direction for my java project. The purpose of this project is to read a text-file, and input the valid dates (text-file has a list of dates) into a linked list, and then display the linked list using a JFrame.

So far I have a class called Date212 whose constructor has a string parameter. The purpose of this constructor is to read the text-file, and parse the Date which is in a String format into 3 integers variable, and do some error checking.

Code for this class can be found here.

My professor instructed us to created another class, DateNode, for the linked class which has two nodes. One to store the dates from ABC, and another pointer to point to the next node. We were also instructed to create a constructor that takes a date as a parameter.

public class DateNode
    protected Date212 temp;
    protected DateNode next;

    public DateNode(Date212 anotherTemp)
        temp = anotherTemp;
        next = null;

Next we were told to create another linked list, DateList, and modify so that the data type in the nodes is ABC, and create a no-argument constructor that creates an empty list with first and last pointing to an empty head node, and length = 0. And a method myAdd that adds the new node to the end of the list.

public class DateList {
    private DateNode first;
    private DateNode last;
    private int length;


    public DateList()
        DateNode x = new DateNode(null)
        first = x;
        last = x;
        length = 0;

    public void myAdd(DateNode lastTemp)
        DateNode firstTemp = new DateNode(lastTemp)
        last.next = firstTemp;
        last = firstTemp;
        length++

Now here's where I am confused. We are supposed to call upon these classes in my main class, Main, which I have no idea how to call. So far in my Main, I have:

public static void main(String args[]) {
    Date212 xyz = new Date212("text.txt")
    DateList myList = new DateList()
    // Trying to add the data from ABC into my linked list.
    myList.myAdd(xyz)

After that I am completely lost as to what I am supposed to do. Does my above code actually add the data from the text-file into my linked list?

Edit: I am not worried about printing it out on a JFrame at the moment, because I am confident that I can do that part easily at the end.

Top answer
1 of 3
2
I will now use meaningful names for classes if you don't mind, so it makes more sense. First of all,we need to start with creating a single link, or a Node (or your "DEF" object). public class Node { Date data; // the payload, which will be a single date entry from the text file Node next; //pointer to the next link in chain Node prev; //pointer to the previous link in chain public Node(Date date) { //a constructor that takes a Date value as parameter and stores it in a link, pointing to nothing this.data = date; this.next = null; this.prev = null; } } A doubly-linked list will maintain a chain of Nodes and keep track of its size: class MyLinkedList { int size; Node head; //we need to know where to start from, so we keep a reference to the first link Node tail; //pointer to the end of the list //..other methods, including addNode(), removeNode(), //get(index), isEmpty(), etc. } The assignment requires to keep two sentinel nodes as well - i.e. empty head and tail nodes. Sentinels contain no payload (no data) and are pointing to nulls, just so we can safely reach the end of the list and avoid a NullPointerException. I don't want to do your entire homework for you, so I recommend you read up on doubly linked list implementation with sentinel nodes in your textbook/lecture notes. If you don't have any for some reason, here's a quick reference you can use or just google "java doubly linked list implementation example" anywhere. Next, you're gonna tie it all together - read text from a file line by line, extract each date, wrap it in a single Node and add the Node to the linked list. To read data from a file, google "java Scanner" examples, it's fairly easy. Then depending on the file's format, you will need to figure out how to extract a single date from a line of input. But the lines you read are of type String (or simple text). In my example I'm assuming thre's no more data in a single line but a single date in plain text format. To convert a String to a valid Date (not sure if required, but you mentioned error checks so I'm assuming it is) you might want to use the DateFormat.parse(String) method and handle the ParseException as your prof's heart desires. Here's how it should go in a nutshell: public class ABC { String myFile; public ABC(String myFile) { this.myFile = myFile; } The reason I don't put the input code inside the constructor is that it's considered a bad practice. Constructors should return very fast and avoid using methods that can throw IO exceptions - in this particular case at least (until you learn about finalizers and such)/ Instead, I took the input out to the separate method doInput() which will return a ready-made LinkedList made of your text file data: public MyLinkedLIst doInput() { //use Scanner to read from myFile, convert each line to a Date //and wrap it in a Node: Scanner myScanner = null; try { myScanner = //instantiate a Scanner object here with //the passed file name (myFile) MyLinkedList myList = new MyLinkedList(); while (myScanner.hasNextLine()) { String line = //read next line from the scanner try { Date myDate = DateFormat.parse(line.trim()); Node node = //wrap myDate in a Node instance myList.add(node); catch (ParseException e) { System.out.println("Could not parse line " + line); } catch (IOException e) { System.out.println("ERROR: Could not open file " + myFile); } } Then in a main() method somewhere, be it your ABC class, or somewhere else, you will instantiate an object of type ABC with your textfile name as a single argument, and call doInput() on it to receive a linked list of dates to do with as you please. All you have to do now is implement the MyLinkedList class as mentioned above. (and then display it with JFrame but that part I hope you can handle yourself').
2 of 3
1
You haven't actually written any implementation to read from a file, all you're doing so far is pass a String to your ABC object. Your class names are absolutely horrendous as well, and I have no idea why your professor makes you implement your own linkedList, twice, when the Java standard library has a perfectly functional linkedList implementation. I would ask you first give your classes a proper identifying name (what are they??), and then I can help you further.
Discussions

java - Creating Linked List from Contents of a File? - Stack Overflow
I'm trying to create a grocery list based on ingredients and inventory. The program is supposed to ask the user for a file that has the ingredients that are needed (meal plan file), then it asks th... More on stackoverflow.com
🌐 stackoverflow.com
February 10, 2019
In this question, you will write a linked list class, and use it to store all of the words contained in a text file. You will write your linked list class in a file called LinkedList.java, which will contain BOTH the LinkedList class and the Node class (only the LinkedList class is public). You have been provided with a main program file called A4Test.java
Answer to In this question, you will write a linked list class, More on chegg.com
🌐 chegg.com
1
July 10, 2016
How to print out a linkedList from a text file in java - Stack Overflow
I can't seem to figure out how to create a linked list from a text file and print out the numbers into a linked list from the text file. if Someone can help me out. what i'm missing. This is my co... More on stackoverflow.com
🌐 stackoverflow.com
November 15, 2019
New to Java: Read data file, create linked list from file. - Oracle Forums
Hello. I just started programming in Java. I've read tutorials on creating a linked list and for reading a simple file with output. Though I'm confused on how to read the file and create a singly-link... More on forums.oracle.com
🌐 forums.oracle.com
May 16, 2008
🌐
Javaprogrammingforums
javaprogrammingforums.com › whats-wrong-my-code › 29197-creating-linked-list-contents-file.html
Creating a Linked List from the contents of a file
June 5, 2013 - Hi, I'm working on an assignment for programming class where we're supposed to create a method that takes the contents from a text file (one giant string) and stores them piece by piece in a linked list. I'm a little stuck and not sure where to go from here, or if I'm on the right track... import java.util.*; import java.io.File; import java.io.FileNotFoundException; public class LinkedLists { // instance variables - not sure if I should use these?
🌐
Karel++
csis.pace.edu › ~wolf › LinkedList › LinkedList.html
Linked List Methods
/* This class reads data from a file and stores it in a linked list. It then displays the data on the screen, finds an ID, deletes a node, and then stores the data in a second file. */ import java.io.*; import list.ListClass; import list.Node; class TestList { public static void main (String [] args) { ListManager manager = new ListManager (); manager.fillList (); manager.displayList (); manager.findNode (); manager.deleteNode (); manager.storeList (); } } // class TestList ·
🌐
Chegg
chegg.com › engineering › computer science › computer science questions and answers › in this question, you will write a linked list class, and use it to store all of the words contained in a text file. you will write your linked list class in a file called linkedlist.java, which will contain both the linkedlist class and the node class (only the linkedlist class is public). you have been provided with a main program file called a4test.java
Solved In this question, you will write a linked list class, | Chegg.com
July 10, 2016 - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class LinkedList { private Node first; private Node last; private int size; public LinkedList() { first = null; last = null; size = 0; } public LinkedList(String fileName) { this(); readFile(fileName); } public int size() { return size; } public void append(String data) { Node newNode = new Node(data); if (isEmpty()) { first = newNode; } else { last.setNext(newNode); } last = newNode; size++; } public String format(int width) { StringBuilder formattedText = new StringBuilder(); Node current = first; in
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 58884308 › how-to-print-out-a-linkedlist-from-a-text-file-in-java
How to print out a linkedList from a text file in java - Stack Overflow
November 15, 2019 - If it's the latter you need to define the type of list. Something like LinkedList<Integer> list = new LinkedList<Integer>();. Similarly for all the places you declare a lined list (including the return value of your list method).
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 446826 › help-with-reading-from-a-file-into-a-linked-list
java - Help with reading from a file into a linked ... | DaniWeb
September 22, 2015 - try (Scanner sc = new Scanner(new File("lab2.dat"), "UTF-8")) { Node head = null, tail = null; int size = 0; while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.isEmpty()) continue; // skip blanks if (line.matches("\\*+")) break; // line of only asterisks => stop Node n = new Node(line, null); // append to singly linked list if (head == null) { head = tail = n; } else { tail.setNext(n); tail = n; } size++; } // head is the first name node; size is the count } ... Your Node() constructor references immunity, which is undefined and will not compile; remove it or add the field. If you also import java.util.*, naming your own class LinkedList can conflict with java.util.LinkedList.
🌐
Oracle
forums.oracle.com › ords › r › apexds › community › q
New to Java: Read data file, create linked list from file. - Oracle Forums
May 16, 2008 - Hello. I just started programming in Java. I've read tutorials on creating a linked list and for reading a simple file with output. Though I'm confused on how to read the file and create a singly-link...
🌐
YouTube
youtube.com › dr. parag shukla
Linked List Part-13 (Reading From File and Writing the same into Linked List) - Practical Demo - YouTube
This video demonstrates how to read from file and writing the same into linked list. This video show practically how to read the one by one data from file an...
Published: January 29, 2022
Views: 10K
🌐
Stack Overflow
stackoverflow.com › questions › 16247277 › how-to-read-from-a-file-save-the-content-into-a-linked-list
java - how to read from a file & save the content into a linked list? - Stack Overflow
public class ListItems { private Node first; public ListItems(){ first=null; } public boolean isEmpty(){ return first==null; } public void addAnItems(Item d, int i){ Node node1=new Node(d); node1.next=first; first=items.get(i); } public void displayList(){ Node current = first; while(current != null){ System.out.println(current.toString()); current=current.next; } } } ... import java.io.* ; import java.util.* ; public class FileItems { public static void main (String[]args){ Scanner input1=new Scanner(System.in) ; try { Scanner input2=new Scanner(new File("items.txt")) ; } catch (FileNotFoundE
🌐
Stack Overflow
stackoverflow.com › questions › 16018872 › java-linked-listed-with-file
Java Linked Listed with File - Stack Overflow
util.*; import java. io.*; public class Assignment2{ public static void main(String args[]){ File text = new File("frame.ini"); LinkedList<Integer> list = new LinkedList<Integer>(); try{ Scanner f= new Scanner (new File("frame.ini")); while (f.hasNext()){ list.add(f.nextInt()); } int maxi= 0; for (int i= 0; i<list.size(); i++){ if ( list.get(i)>maxi) maxi=list.get(i); } System.out.println("Maximum Number : "+maxi); int mini= maxi; for (int i= 0; i<list.size(); i++){ if ( list.get(i)<mini) mini=list.get(i); } System.out.println("Minimum Number : "+mini); int n=0; for (int i= 0; i<list.size(); i++){ n=n + list.get(i); } int Total= n; System.out.println("Tally of Numbers: "+Total); int sum = 0; for (int i= 0; i<list.size(); i++){ sum = sum + list.get(i); } int avg = sum /list.size(); System.out.println("Average of Numbers: "+avg); } catch (IOException e){ } } }
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 353418 › help-text-file-to-linkedlist
java - Help: Text file to LinkedList | DaniWeb
March 15, 2011 - The constructor is to create an object instance of the class and the variables are for you to store necessary data to be used later (such as sort, print out, etc.). // Below is an example of how to construct your FileLine class. // The variable 'ArrayList' may be used if you want, or you can use // other type of List. import java.util.ArrayList; public class FileLine { String filename; ArrayList<Integer> numberArray; // a sample constructor public Fileline(String str) { filename = str; numberArray = new ArrayList<Integer>(); } // I am not sure about having this method throwing 'Exception'.
🌐
Oracle Communities
community.oracle.com › thread › 1191216
New to Java: Read data file, create linked list... | Oracle Community
Hello. I just started programming in Java. I've read tutorials on creating a linked list and for reading a simple file with output. Though I'm confused on how to read the file and create a singly-linked string list from it. I've gone through some examples but they have always been manually inserting into the list rather than from a file.
🌐
Java-forums
java-forums.org › new-java › 72575-creating-linked-list-contents-file.html
New To Java
New To Java - New to Java technology and you want to learn Java? Do you have a Java question and don't know which forum is appropriate for it. Then
🌐
Stack Overflow
stackoverflow.com › questions › 29436448 › how-to-read-data-from-a-textfile-and-add-it-to-a-linked-list
java - How to read data from a textfile and add it to a linked list - Stack Overflow
int i = 1; // this variable is used to know on which line the reader is on while((line = reader.readLine()) != null) { if(line.trim().equals("")) // if the line is a new line then add the previous patient to the list and create a new patient, re initialize i = 0 { list.add(patient); patient = new Patient(); i = 1; } else { if(i == 1) // on first line of the file set the patients name { patient.set_name(line); } else if(i == 2)//on second line of the file set the patients ID Number { patient.set_patientIDNumber(line); } // add else if for other attributes on other lines i++; } } list.add(patient); reader.close(); }catch(IOException e) { e.printStackTrace(); } }
🌐
Stack Overflow
stackoverflow.com › questions › 27680720 › linked-list-contains-lines-from-a-text-file-create-findint-index-method-which
java - Linked List contains lines from a text file. Create find(int index) method which prints the content at the index positions passed as an argument - Stack Overflow
import java.util.Scanner; import java.io.FileReader; import java.io.FileNotFoundException; public class ContactMain{ public static void main(String[]args){ try{ FileReader filepath = new FileReader("data1.txt"); Scanner k = new Scanner(filepath); ContactList myList = new ContactList(); while (k.hasNextLine()){ String i = k.nextLine(); myList.addNode(new ContactNode(i));} myList.traverse(); myList.getFirst(); myList.getLast(); myList.find(3); }catch (FileNotFoundException e){ System.out.println("File Not Found. ");}}} ... This find method doesn't return anything. I am trying to make it so the u