List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Read Data from a File in Java?

Read File Example

Condition for Reading Data from a File in Java

  • Description: Reading data from a file in Java involves utilizing classes from the java.io or java.nio.file packages. Commonly used classes include FileReader and BufferedReader for reading text files, where FileReader opens the file and BufferedReader reads the content line by line, improving efficiency by buffering input. The readLine method retrieves each line until the end of the file is reached. For reading binary data, FileInputStream is used, reading byte-by-byte or into a byte array. In modern approaches, Files from java.nio.file simplifies reading files with methods like readAllLines or readAllBytes, returning the content as a list of strings or a byte array. Ensuring proper resource management involves using try-with-resources to automatically close streams and handle exceptions gracefully.
Sample Source Code
  • # ReadDataFile.java
    package JavaSamples;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;

    public class ReadDataFile extends javax.swing.JFrame {
    public ReadDataFile() {
    initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
    // UI setup code
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    int result = fileChooser.showOpenDialog(this);
    if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField1.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField1.setText("No File Selected ");
    }
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    String filePath = jTextField1.getText();
    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
    String line;
    while ((line = reader.readLine()) != null) {
    jTextArea2.setText(line);
    }
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
    new ReadDataFile().setVisible(true);
    });
    }
    }
Screenshots
  • STEP 1: The user selects a text document from local files.
  • Select File Dialog

  • STEP 2: The file path will be displayed in the text field after the file is selected.
  • Display File Path

  • STEP 3: The user can read the content of the file by selecting the "Read from File" button, displaying the file content in the text area.
  • Display File Content

Related Links