如何从文件填充对象数组?解决BufferedReader实现时的数组越界问题
排查Java BufferedReader填充对象数组的数组越界问题及解决方案
Let's break down the issues in your code one by one and fix them, plus offer some alternative approaches to make this more robust.
核心问题导致数组越界
Your ArrayIndexOutOfBoundsException stems from two critical mistakes:
- Index reset inside the loop: You initialize
int i = 0;inside thewhileloop, so every time you read a line, you're overwritingarbook[0]instead of moving to the next index. Worse, when you hit the final comment line ((( Name,Author,Released,numCopies,properAge,science <boolean> ))), splitting this line with" "gives an array with only 1 element—trying to accessar[1]here throws the exception. - Unfiltered input: Your code attempts to process every line in the file, including the non-data comment line that doesn't follow the 5-field format.
其他需要修正的代码问题
Beyond the exception, there are a few other issues violating Java conventions or best practices:
- Case sensitivity: Java is case-sensitive. You declared your array as
static book arbook[], but your class is namedBook(capital B)—this will cause a compilation error. - Resource leak: You don't close your
BufferedReader, which can lead to resource leaks. Use try-with-resources to handle this automatically. - Hardcoded array size: You set
arbookto size 14, but if your file ever has more or fewer valid lines, this will cause new errors. - CamelCase inconsistencies: Your
properAgegetter is namedgetProperage(missing capital A), which breaks Java naming conventions.
修正后的完整代码
Here's the fixed version that addresses all these issues:
import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class BooksReader { // Fix class name case, use a static index to track position static Book arbook[] = new Book[14]; static int currentIndex = 0; public static void array_filler() throws FileNotFoundException { // Try-with-resources auto-closes BufferedReader try (BufferedReader br = new BufferedReader(new FileReader("MyPath"))) { String line; while ((line = br.readLine()) != null) { // Skip empty lines and the final comment line if (line.isBlank() || line.startsWith("((")) { continue; } String[] ar = line.split(" "); // Validate line has exactly 5 fields before processing if (ar.length != 5) { System.out.println("Skipping invalid line: " + line); continue; } try { // Assign to current index and increment arbook[currentIndex] = new Book( ar[0], ar[1], Integer.parseInt(ar[2]), Integer.parseInt(ar[3]), Integer.parseInt(ar[4]) ); currentIndex++; } catch (NumberFormatException e) { System.out.println("Invalid number format in line: " + line); } } } catch (IOException ex) { Logger.getLogger(BooksReader.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) throws FileNotFoundException { BooksReader.array_filler(); } } // Ensure class name is consistent (capital B) class Book { private String bookName; private String bookAuthor; private String serialNumber; // Renamed to camelCase private int numCopies; private int properAge; private int bookReleaseDate; public Book(String bookName, String bookAuthor, int bookReleaseDate, int numCopies, int properAge) { this.bookName = bookName; this.bookAuthor = bookAuthor; this.bookReleaseDate = bookReleaseDate; this.numCopies = numCopies; this.properAge = properAge; } // Fixed getter name for properAge public String getBookName() { return bookName; } public int getNumCopies() { return numCopies; } public int getProperAge() { return properAge; } public void setBookName(String bookName) { this.bookName = bookName; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } public void setReleaseDate(int bookReleaseDate) { this.bookReleaseDate = bookReleaseDate; } public void setNumCopies(int numCopies) { this.numCopies = numCopies; } public void setProperAge(int properAge) { this.properAge = properAge; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public boolean checkAge(int ageOfUser) { return ageOfUser >= properAge; } public int addNumCopies() { return ++this.numCopies; } public int decNumCopies() { return --this.numCopies; } }
更灵活的替代实现思路
For a more maintainable solution, consider these alternatives:
- Use
ArrayList<Book>instead of a fixed array: This eliminates hardcoded size limits and handles variable numbers of entries automatically:static List<Book> books = new ArrayList<>(); // Replace array assignment with: books.add(new Book(...)); - Use
Scannerfor simpler token parsing: Scanner is built for reading tokenized input and can avoid manual string splitting:try (Scanner scanner = new Scanner(new File("MyPath"))) { while (scanner.hasNext()) { String bookName = scanner.next(); String author = scanner.next(); int releaseDate = scanner.nextInt(); int numCopies = scanner.nextInt(); int properAge = scanner.nextInt(); books.add(new Book(bookName, author, releaseDate, numCopies, properAge)); // Skip the final comment line if (scanner.hasNextLine() && scanner.nextLine().startsWith("((")) { break; } } } - Use a CSV library: If your file might later include spaces in titles/author names, libraries like OpenCSV can handle proper parsing without manual split logic.
内容的提问来源于stack exchange,提问作者Yusuf Abdelfattah
相关产品推荐
相关产品推荐

