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

Office Address

Social List

How to Write Data into a File in Java?

Write File Example

Condition for Writing Data into a File in Java

  • Description: Writing data to a file in Java involves using classes from the java.io or java.nio.file packages. FileWriter is commonly used for writing text data, often paired with BufferedWriter for efficient, buffered output. The write method allows data to be written as strings or characters, and newLine can be used to insert line breaks when writing multiple lines. For binary data, FileOutputStream writes bytes or byte arrays directly to the file. The PrintWriter class provides additional formatting options for writing formatted text, such as using printf or println. In modern Java, Files from java.nio.file simplifies writing data with methods like write, which can write a list of strings or byte arrays directly. Using try-with-resources ensures proper resource management by automatically closing the file streams and handling exceptions efficiently.
Sample Source Code
  • # WriteDataFile.java
    package JavaSamples;

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import javax.swing.JOptionPane;

    public class WriteDataFile extends javax.swing.JFrame {
    public WriteDataFile() {
    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();
    String input = jTextArea1.getText();
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
    writer.write(input);
    writer.newLine();
    JOptionPane.showMessageDialog(null, "Writed into File successfully");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
    new WriteDataFile().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 input data into the text area and click "Write" to save it to the file.
  • Write Content

Related Links