杰瑞科技汇

Java input文件操作如何实现?

Of course! The term "input file" in Java can refer to two main things:

  1. Reading data from a file into your Java program. This is the most common meaning. It involves using Java's I/O (Input/Output) libraries to read the contents of a file.
  2. A file that contains input for a command-line Java program. This is a common pattern where a program expects a filename as an argument when it's run.

Let's break down both, starting with the most common one: reading a file.


Reading Data from a File (The Core Concept)

There are several ways to read a file in Java, ranging from classic, fundamental approaches to modern, concise ones. The best method depends on your specific needs (e.g., file size, Java version, whether you need the whole file at once or line-by-line).

Here are the most popular methods, ordered from modern/advanced to classic/fundamental.

Method 1: java.nio.file (Modern & Recommended - Java 7+)

This is the current standard and the most flexible way to handle files. It's non-blocking (which is great for performance) and generally easier to use correctly.

a) Reading All Lines at Once (Simple & Great for Small/Medium Files)

This is the easiest way to get the entire content of a file into a List<String>.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class ReadAllLinesExample {
    public static void main(String[] args) {
        // Define the path to your file
        Path path = Paths.get("my-data.txt");
        try {
            // Read all lines from the file into a List
            List<String> lines = Files.readAllLines(path);
            // Print each line
            System.out.println("File content:");
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // Handle potential I/O errors (e.g., file not found)
            System.err.println("Error reading the file: " + e.getMessage());
        }
    }
}

How to Run:

  1. Save the code as ReadAllLinesExample.java.
  2. Create a file named my-data.txt in the same directory with some content, for example:
    Hello, Java!
    This is a test file.
    We are reading it using NIO.
  3. Compile and run:
    javac ReadAllLinesExample.java
    java ReadAllLinesExample

b) Reading Line-by-Line (Memory Efficient for Large Files)

If you're dealing with a very large file, loading it all into memory at once is a bad idea. Using a BufferedReader with NIO is the perfect solution.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadLineByLineExample {
    public static void main(String[] args) {
        Path path = Paths.get("my-data.txt");
        // The try-with-resources statement ensures the reader is closed automatically
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            String line;
            System.out.println("File content (line by line):");
            // Read until we reach the end of the file (line == null)
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }
    }
}

Method 2: java.io (Classic Approach - Pre-Java 7)

This is the "old school" way. It's more verbose but is still important to know, especially if you're working on older projects.

a) Using FileReader and BufferedReader

This is the classic line-by-line reading pattern. Always wrap a FileReader in a BufferedReader for performance.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ClassicReadExample {
    public static void main(String[] args) {
        // The try-with-resources statement handles closing the resources
        try (BufferedReader reader = new BufferedReader(new FileReader("my-data.txt"))) {
            String line;
            System.out.println("File content (classic approach):");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }
    }
}

The "Input File" as a Command-Line Argument

This is a very common pattern where your program is designed to accept the path of the input file as an argument when it's executed from the command line.

The main method has an array of strings, args, which holds these arguments.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class ArgumentInputFile {
    public static void main(String[] args) {
        // 1. Check if an argument was provided
        if (args.length == 0) {
            System.out.println("Error: Please provide a filename as an argument.");
            System.out.println("Usage: java ArgumentInputFile <filename>");
            return; // Exit the program
        }
        // 2. The first argument (at index 0) is the filename
        String fileName = args[0];
        System.out.println("Attempting to read file: " + fileName);
        try {
            // 3. Read all lines from the file provided in the argument
            String content = Files.readString(Paths.get(fileName));
            System.out.println("\n--- File Content ---");
            System.out.println(content);
            System.out.println("--------------------");
        } catch (IOException e) {
            System.err.println("Error: Could not read the file '" + fileName + "'.");
            System.err.println("Reason: " + e.getMessage());
        }
    }
}

How to Run:

  1. Save the code as ArgumentInputFile.java.

  2. Create my-data.txt as before.

  3. Compile the code.

  4. Run it, passing the filename as an argument:

    # Compile
    javac ArgumentInputFile.java
    # Run (Correct usage)
    java ArgumentInputFile my-data.txt
    # Run (Incorrect usage - will show the error message)
    java ArgumentInputFile

Summary: Which Method to Use?

Scenario Recommended Method Why?
Quickly read a small file Files.readAllLines() (NIO) Concise, easy to read, and highly efficient for small to medium-sized files.
Read a large file line-by-line Files.newBufferedReader() (NIO) with a while loop Memory efficient. Doesn't load the whole file into RAM.
Simple binary file reading Files.readAllBytes() (NIO) The easiest way to get all raw bytes from a file.
Reading a file path from the console Use main(String[] args) + any of the above methods This is the standard way to pass parameters to a command-line program.
Working on an old Java project (Java 6 or earlier) new BufferedReader(new FileReader(...)) (Classic IO) This is the only available method. The modern NIO API was introduced in Java 7.
Maximum performance/advanced needs java.nio.channels.FileChannel Offers more control, like reading/writing specific parts of a file (regions) and memory-mapped files.
分享:
扫描分享到社交APP
上一篇
下一篇