Skip to content

Instantly share code, notes, and snippets.

@maf946
Created November 30, 2022 14:58
Show Gist options
  • Save maf946/346789b48d0fc3c00e2cc5df324df3f5 to your computer and use it in GitHub Desktop.
Save maf946/346789b48d0fc3c00e2cc5df324df3f5 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static ArrayList<String> readFile(){
String fileName = "textFile.txt";
ArrayList <String> namesArrayList = new ArrayList();
File fileToRead = new File(fileName);
Scanner scnr = null;
String nextLine = "";
try
{
scnr = new Scanner(fileToRead);
while(scnr.hasNextLine()){
nextLine = scnr.nextLine();
namesArrayList.add(nextLine);
}
}
catch(FileNotFoundException fne)
{
String errorString = fne.getMessage();
System.out.println(errorString);
}
finally{
if(scnr != null){
scnr.close();
}
}
return namesArrayList; // names in the file
}
public static void main(String[] args)
{
ArrayList<String> fileContents = readFile();
for (String element: fileContents)
{
System.out.println(element);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment