在Java中,读取文件数组中的内容可以通过以下几种方法实现:
1. 读取整数数组:
import java.io.FileInputStream;import java.io.DataInputStream;import java.io.IOException;public class ReadIntArrayFromFile {public static void main(String[] args) {int[] myArray = new int; // 预期文件中的整数数量try {FileInputStream fileInputStream = new FileInputStream("path_to_file");DataInputStream dataInputStream = new DataInputStream(fileInputStream);for (int i = 0; i < myArray.length; i++) {myArray[i] = dataInputStream.readInt();}dataInputStream.close();fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
2. 读取字节数组:
import java.io.FileInputStream;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;public class ReadBytesFromFile {public static void main(String[] args) throws IOException {Path path = Paths.get("path_to_file");byte[] contents = Files.readAllBytes(path);// 使用contents进行后续操作}}

3. 按行读取文件并存储到字符串数组:
import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class ReadDataFromFile {public static void main(String[] args) {File file = new File("data.txt");ListdataList = new ArrayList<>(); try {Scanner scanner = new Scanner(file);while (scanner.hasNextLine()) {dataList.add(scanner.nextLine());}scanner.close();} catch (FileNotFoundException e) {e.printStackTrace();}// 将ArrayList转换为数组(如果需要的话)String[] dataArray = dataList.toArray(new String);}}
4. 按行读取文件并存储到字符串列表:
import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class ReadFileToList {public static ListreadFileToList(String filePath, String fileName) { Listlist = new ArrayList<>(); try {File file = new File(filePath + "/" + fileName);if (file.isFile() && file.exists()) {InputStreamReader read = new InputStreamReader(new FileInputStream(file));BufferedReader bufferedReader = new BufferedReader(read);String lineTxt = null;while ((lineTxt = bufferedReader.readLine()) != null) {list.add(lineTxt);}read.close();}} catch (Exception e) {e.printStackTrace();}return list;}}
请根据您的具体需求选择合适的方法。
