在Java中读取文件并存入数组可以通过多种方式实现,以下是几种常见的方法:
方法一:使用`BufferedReader`和`ArrayList`
import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;public class FileToArray {public static ArrayListreadTxtFile(String filepath) { ArrayListlines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(filepath))) {String line;while ((line = reader.readLine()) != null) {lines.add(line);}} catch (IOException e) {e.printStackTrace();}return lines;}public static void main(String[] args) {ArrayListlines = readTxtFile("path/to/your/file.txt"); for (String line : lines) {System.out.println(line);}}}
方法二:使用`FileInputStream`和字节数组
import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class FileToByteArray {public static byte[] readFileToByteArray(String filepath) throws IOException {File file = new File(filepath);byte[] bytesArray = new byte[(int) file.length()];try (FileInputStream fis = new FileInputStream(file)) {fis.read(bytesArray);}return bytesArray;}public static void main(String[] args) {try {byte[] bytes = readFileToByteArray("path/to/your/file.txt");String content = new String(bytes);System.out.println(content);} catch (IOException e) {e.printStackTrace();}}}
方法三:使用`Scanner`类
import java.io.File;import java.util.ArrayList;import java.util.Scanner;public class FileToScanner {public static ArrayListreadFileWithScanner(String filepath) { ArrayListlines = new ArrayList<>(); try (Scanner scanner = new Scanner(new File(filepath))) {while (scanner.hasNextLine()) {lines.add(scanner.nextLine());}}return lines;}public static void main(String[] args) {ArrayListlines = readFileWithScanner("path/to/your/file.txt"); for (String line : lines) {System.out.println(line);}}}
方法四:使用`FileChannel`和`MappedByteBuffer`
import java.io.File;import java.io.IOException;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;public class FileToByteBuffer {public static byte[] readFileToByteBuffer(String filepath) throws IOException {File file = new File(filepath);long fileSize = file.length();if (fileSize > Integer.MAX_VALUE) {System.out.println("File is too big");return null;}try (FileChannel fileChannel = new FileInputStream(file).getChannel()) {MappedByteBuffer buffer = fileChannel.map(MapMode.READ_ONLY, 0, fileSize);byte[] bytesArray = new byte[buffer.remaining()];buffer.get(bytesArray);return bytesArray;}}public static void main(String[] args) {try {byte[] bytes = readFileToByteBuffer("path/to/your/file.txt");String content = new String(bytes);System.out.println(content);} catch (IOException e) {e.printStackTrace();}}}
以上方法展示了如何使用不同的I/O类来读取文件内容并存入数组。你可以根据具体需求选择合适的方法。需要注意的是,读取大文件时,应考虑内存使用情况,避免内存溢出
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/91825.html