You can do something like this:

BufferedReader reader = new BufferedReader(new FileReader(<<your file>>));
List<String> lines = new ArrayList<>();
String line = null;
while ((line = reader.readLine()) != null) {
    lines.add(line);
}

System.out.println(lines.get(0));

With BufferedReader you are able to read lines directly. This example reads the file line by line and stores the lines in an array list. You can access the lines after that by using lines.get(lineNumber).

Answer from micha on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java io › reading a csv file into an array
Reading a CSV File into an Array | Baeldung
May 9, 2025 - One option would be to use a custom CSV parser that reads line by line and uses a StringBuilder to fetch each value. An advantage of using this approach is being able to use a CSV file with commas embedded within values, along with a comma delimiter:
Discussions

Reading CSV file.
You are using a relative path, so the jvm is looking at ${project dir}/Files/Crimes.csv. so if your project folder is called MyProject and located under C:/, then the jvm is looking for the file at C:/MyProject/Files/Crimes.csv. If the file is not there, you should use the absolute path. You can check exactly where you are telling the jvm the file is located by adding the following print statement. System.out.println(new File(file).getAbsolutePath()). For readability, change the variable name File to something else. You are using the actual File class, so having a variable name the same will only confuse you or others later. I would name it crimesFileName, that tells anybody reading it what exactly it is. Leaving it as File forces the reader to track back to where it is originally declared. More on reddit.com
🌐 r/learnjava
5
8
May 29, 2023
Reading one specific line from CSV file
"Jumping" is not possible in a CSV file as file access is generally sequentially. Basically, all you can do is linear search. Yet, in such a case, if the number of entries (People instances) is not too high, it is preferable to store the entries in memory (ArrayList, HashMap) on startup and if changed save them to drive before application end (or after changes). If you wanted a search functionality, you should rather use a proper database (H2, HSQL, SQLite - all serverless, or a server based DB) - import the CSV into a DB. More on reddit.com
🌐 r/javahelp
4
1
August 27, 2022
java - How do I efficiently read random lines from a TXT or CSV file? - Software Engineering Stack Exchange
To get some randomness in your ... in the file and move forward or backward to the next record by looking for a line separator. However, you will not know which record it is. Moreover, if you use the CSV variant defined in RFC4180, this will not work, because line separators can be part of a field if it is enclosed between quotes, and you wouldn’t know if there wasn’t such an unclosed opening quote before. The only way is then to read the file from ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 16, 2021
How to read and print only specific rows of a CSV file?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
9
2
November 30, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › java › reading-csv-file-java-using-opencsv
Reading a CSV file in Java using OpenCSV - GeeksforGeeks
July 11, 2025 - BeanToCsv - This class helps to ... your java application. ... For reading a CSV file you need CSVReader class. Following are sample CSV file that we’ll read. name, rollno, department, result, cgpa amar, 42, cse, pass, 8.6 rohini, 21, ece, ...
🌐
Medium
medium.com › @zakariafarih142 › mastering-csv-parsing-in-java-comprehensive-methods-and-best-practices-a3b8d0514edf
Mastering CSV Parsing in Java: Comprehensive Methods and Best Practices | by Zakariafarih | Medium
November 25, 2024 - While this approach reduces dependencies, it requires careful handling of edge cases. Overview: Read the CSV file line by line using BufferedReader and split each line based on the comma delimiter.
🌐
Reddit
reddit.com › r/learnjava › reading csv file.
r/learnjava on Reddit: Reading CSV file.
May 29, 2023 -
Ok im trying to read from a csv file and some how my directory can't find it can someone help. The Cvs file is in my project src file which I have named Files as well. 

Heres the code:


 import java.io.BufferedReader;

import java.io.FileReader; import java.io.IOException; import java.io.*; public class Operrations {

public static void main(String[] args) throws Exception {

    String File = "Files\\Crimes.csv";

    BufferedReader reader = null;

    String line = "";

    try {

        reader = new BufferedReader(new FileReader(File));

        while((line = reader.readLine()) !=null);

        String[] row = line.split(",");

        for(String index: row){

            System.out.printf("%-10", index);


        }

        System.out.println();






    




    }


    catch (Exception e){

        e.printStackTrace();



    }


    finally {


        try{


        reader.close();

        } catch(IOException e){

            e.printStackTrace();



        }




    }





}

}

🌐
Mark Needham
markhneedham.com › blog › 2013 › 10 › 14 › java-incrementally-readstream-a-csv-file
Java: Incrementally read/stream a CSV file | Mark Needham
October 14, 2013 - public class ParseCSVFile { public static void main(String[] args) throws IOException { final CSVReader csvReader = new CSVReader( new BufferedReader( new FileReader( "/path/to/file.csv" ) ), '\t' ); final String[] fields = csvReader.readNext(); Iterator<Map<String, Object>>() lazilyLoadedFile = return new Iterator<Map<String, Object>>() { String[] data = csvReader.readNext(); @Override public boolean hasNext() { return data != null; } @Override public Map<String, Object> next() { final Map<String, Object> properties = new HashMap<String, Object>(); for ( int i = 0; i < data.length; i++ ) { properties.put(fields[i], data[i]); } try { data = csvReader.readNext(); } catch ( IOException e ) { data = null; } return properties; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
Find elsewhere
🌐
Coderanch
coderanch.com › t › 713986 › java › Reading-CSV-file-scanner
Reading a CSV file using scanner (Beginning Java forum at Coderanch)
August 4, 2019 - Just be aware that there are valid CSV files out there for which this will break. ... You need to close the Scanner when you're done with it. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
Reddit
reddit.com › r/javahelp › reading one specific line from csv file
r/javahelp on Reddit: Reading one specific line from CSV file
August 27, 2022 -

Hi all! I'm wondering how I could solve the following problem. Let's say I have a .csv file that looks like this:

ID Name
20943 Alice
19782 Bob

I also have a class, let's call it Person :

public class Person {
    private int ID
    private String name

    public Person(int ID, String Name) {
        this.ID = ID;
        this.name = name;
    }
}

Now I'd like to create some sort of PersonDataReader class:

public class PersonDataReader {
    
    public Person createPersonFromData(int line) {

    } 
}

I'd like this createPersonFromData method to jump to the specified line, read the name and ID and then call the constructor of Person with those arguments. How can I achieve something like that?

Top answer
1 of 2
5

CSV files and many other text based formats encode information in a potentially variable size. Due to the variable record size, there is no way to directly jump to a random record if you don’t know its precise position in the file.

To get some randomness in your app, you could imagine to go to a random offset in the file and move forward or backward to the next record by looking for a line separator. However, you will not know which record it is. Moreover, if you use the CSV variant defined in RFC4180, this will not work, because line separators can be part of a field if it is enclosed between quotes, and you wouldn’t know if there wasn’t such an unclosed opening quote before. The only way is then to read the file from the start and parse it record after record.

What you need to do is to construct an index. , as suggested by Killian and Amon in the comments. For example:

  • at start of your programme by parsing your data file, and build in memory an array with the starting position of the record in the file.
  • or, use a separate indexer that parses the file, and created an index file. Each index record is of fixed size and indicates the position of the next record in the main data file. Since the size of index record is fixed, you can locate easily any random record n by going to position n*sizeOfRecord in the index file, read the position of where to find the record in the data file, and start reading the data at this offset.

Remark: this indexing approach works with any variable length encoding. It could be multiline files, or even complex formats such as json or xml, provided that the indexer can parse the expected format to identify the boundaries of each record.

2 of 2
2

While Christophe's answer addresses the actual question about the random reading of the text files, I think there is a XY problem here.

You have a set of chess puzzles structures in a form of a text file. And so you're asking how to read a random line from this file. Your actual question should instead be how to load a random chess puzzle, given that currently, the puzzles are stored in a given format.

The answer then involves two stages.

The first stage is to find what's the correct format to store the puzzles in the first place. For your needs, the text format is not a correct one. It doesn't allow it easily to load a random puzzle, and it possibly wastes too much disk space anyway. Instead, one may use a relational database. If the data needs to be distributed with your application (i.e. to work in offline mode), SQLite could be a great option. It will handle all the storage details for you, so you would be able to retrieve a puzzle in just one line of code.

NoSQL databases may also be considered, in order to store the puzzle in a very readable (such as JSON), but also very efficient (i.e. compressed) way. This could further simply the code, in your application, which would convert the data received from the database to the actual object in the application itself.

The second stage then is to export the data from the text file, and actually import it to the database.

🌐
CodeSignal
codesignal.com › learn › courses › parsing-table-data-in-java › lessons › parsing-csv-files-in-java-using-jackson-library
Parsing CSV Files in Java Using Jackson Library
By the end of this lesson, you will learn how to read data from CSV files using Java's Jackson library, which provides tools for data parsing and handling. This lesson builds on your existing knowledge of file parsing in Java and introduces new techniques using the Jackson library to enhance your data-handling capabilities. ... CSV stands for Comma-Separated Values and is a format that stores tabular data in plain text. Each line ...
🌐
Mkyong
mkyong.com › home › java › how to read and parse csv file in java
How to read and parse CSV file in Java - Mkyong.com
December 26, 2020 - Talks about CSV file parsing, RFC 4180, OpenCSV and Single class implementation examples to read and parse a CSV file.
🌐
TechVidvan
techvidvan.com › tutorials › read-csv-file-in-java
How to Read CSV file in Java - TechVidvan
July 1, 2020 - Can handle entries that span multiple lines. We use the CSVReader class to read a CSV file. The class CSVReader provides a constructor to parse a CSV file. ... 1: Create a class file with the name CSVReaderDemo and write the following code.
🌐
Coderanch
coderanch.com › t › 771950 › java › Reading-csv-file
Reading csv file (I/O and Streams forum at Coderanch)
April 18, 2023 - Welcome to the Ranch In most real‑life applications one wouldn't read a CSV directly, but use a program designed to cope with CSVs. Obviously your assignment forces you to read the file “by hand”. How you do that depends on the format of the file and what delimiters you are using. I would suggest you initialise the List in the constructor. You cannot be sure that a setXXX() method will ever be called and your object will be created in an inconsistent state. I would also have used a Scanner to parse the lines.
🌐
TutorialsPoint
tutorialspoint.com › how-to-read-the-data-from-a-csv-file-in-java
How to read data from .csv file in Java?
July 1, 2020 - import java.io.FileReader; import com.opencsv.CSVReader; public class ReadFromCSV { public static void main(String args[]) throws Exception { //Instantiating the CSVReader class CSVReader reader = new CSVReader(new FileReader("D://sample.csv")); //Reading the contents of the csv file StringBuffer buffer = new StringBuffer(); String line[]; while ((line = reader.readNext()) != null) { for(int i = 0; i<line.length; i++) { System.out.print(line[i]+" "); } System.out.println(" "); } } }
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-read-file-line-by-line
Java Read File: Complete Guide with Examples | DigitalOcean
February 20, 2025 - Continue your learning with the Files API Doc (Java SE 8). You can use RandomAccessFile to open a file in read mode and then use its readLine method to read a file line-by-line.
🌐
YouTube
m.youtube.com › watch
Java read CSV File 📰
Share your videos with friends, family, and the world
🌐
Coderanch
coderanch.com › t › 275822 › java › read-csv-file
how to read the .csv file (I/O and Streams forum at Coderanch)
September 23, 2002 - Hi! Java by itself does not offer read-made solutions to read a CSV file. Use a buffered Reader to read the file line by line. And for each line use the StringTokenizer class to get the individual column values.
🌐
YouTube
youtube.com › watch
How to Read a Column From a CSV/TXT File Using Java - YouTube
How to Read a Column From a CSV/TXT File Using JavaGreetings, today we are here with a tutorial on how to read a column from your csv, text file and many oth...
Published   May 16, 2022
Views   7K
🌐
YouTube
youtube.com › watch
Handling CSV Files in Java | Writing & Reading CSV File | Part 4 - YouTube
######################################### 🚀 Udemy Courses 👨‍💻👩‍💻##########################################🟢 Playwright with Typ...
Published   October 19, 2023
🌐
HCL GUVI
studytonight.com › java-examples › reading-a-csv-file-in-java
Reading a CSV File in Java
FixTheCode is a series of programs curated by industry experts. Helps you get started and become familiar with programming. Your performance in FixTheCode influences job recommendations. Enhances your programming skills and improves interview success.Explore FixTheCode ... HCL GUVI IDE is an Integrated Development Environment (IDE) for coding. Allows you to write, edit, run, test, and debug your code. Comes with a built-in debugger to fix code errors. Supports JavaScript, Python, Ruby, and 20+ programming languages.Explore IDE