Java

Java Scanner类读取文件内容的技巧

小樊
97
2024-08-07 03:50:23
栏目: 编程语言

使用Java的Scanner类读取文件内容可以非常方便和灵活。以下是一些技巧和示例代码:

  1. 使用Scanner类读取文件内容:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}
  1. 使用Scanner类读取文件内容并按指定分隔符进行分割:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            Scanner scanner = new Scanner(file);
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                String data = scanner.next();
                System.out.println(data);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}
  1. 使用Scanner类读取文件内容并跳过指定数量的行:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            Scanner scanner = new Scanner(file);
            int linesToSkip = 2;
            for (int i = 0; i < linesToSkip; i++) {
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                }
            }
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}

通过以上几种方法,可以灵活地使用Scanner类读取文件内容,并根据需要进行处理和操作。

0
看了该问题的人还看了