Проблемы с чтением файла с помощью Java ⇐ JAVA

Программисты JAVA общаются здесь
Anonymous
Проблемы с чтением файла с помощью Java

Сообщение Anonymous »

У меня проблема с моим кодом, поскольку он позволяет создавать документы, содержащие строки с измерениями, определенными самим кодом. Когда я пытаюсь отобразить их на экране, программа выдает следующую ошибку:
java.io.EOFException
at java.base/java.io.RandomAccessFile.readFully(RandomAccessFile.java:498)
at java.base/java.io.RandomAccessFile.readFully(RandomAccessFile.java:472)
at RandomFileHandlerAlex.decodeFiles(RandomFileHandlerAlex.java:104)
at RandomFileHandlerAlex.main(RandomFileHandlerAlex.java:20)


Я искал способы решить эту проблему, указав измерение, выполнив проверку ошибок, чтобы увидеть, соответствует ли оно измерению или нет, но мне ничего не помогло. Я прилагаю код ниже, чтобы узнать, сможет ли кто-нибудь мне помочь.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;

public class RandomFileHandlerAlex {
public static Scanner input = new Scanner(System.in);

public static void main(String[] args) throws IOException {
int selection = -1;
while (selection != 0) {
showMenu();
selection = input.nextInt();
input.nextLine(); // Clear buffer
if (selection == 1) {
handlePopulations();
} else if (selection == 2) {
handleRegion();
} else if (selection == 3) {
decodeFiles();
} else if (selection == 4) {
modifyFifthPopulationRecord();
} else if (selection == 5) {
addPopulationOrRegion();
}
}
}

// Method to display menu options
public static void showMenu() {
System.out.println("1. Enter populations");
System.out.println("2. Enter region");
System.out.println("3. Decode file");
System.out.println("4. Edit 5th position");
System.out.println("5. Add record");
System.out.println("0. Exit");
}

// Method to handle population input and save it to a file
public static void handlePopulations() {
try (RandomAccessFile file = new RandomAccessFile("population.dat", "rw")) {
Scanner scanner = new Scanner(System.in);
System.out.println("---------Enter populations--------");
file.seek(file.length());
for (int i = 0; i < 8; i++) {
System.out.println("Enter name:");
String name = scanner.nextLine();
name = String.format("%-60s", name); // Set fixed length

System.out.println("Enter number of inhabitants:");
int inhabitants = scanner.nextInt();

System.out.println("Enter rt:");
double rt = scanner.nextDouble();

scanner.nextLine(); // Clear buffer

System.out.println("Enter postal code:");
String postalCode = scanner.nextLine();
postalCode = String.format("%-5s", postalCode);

file.writeUTF(name); // Write name as UTF-8
file.writeInt(inhabitants); // Write inhabitants
file.writeDouble(rt); // Write rt
file.writeUTF(postalCode); // Write postal code as UTF-8
}
} catch (IOException e) {
e.printStackTrace();
}
}

// Method to handle region input and save it to a file
public static void handleRegion() {
try (RandomAccessFile file = new RandomAccessFile("region.dat", "rw")) {
System.out.println("---------Enter regions--------");
file.seek(file.length());
for (int i = 0; i < 8; i++) {
System.out.println("Enter name:");
String name = input.nextLine();
name = String.format("%-30s", name); // Set fixed length

System.out.println("Enter number of inhabitants:");
int inhabitants = input.nextInt();

System.out.println("Enter rt:");
double rt = input.nextDouble();

input.nextLine(); // Clear buffer

file.writeUTF(name);
file.writeInt(inhabitants);
file.writeDouble(rt);
}
} catch (IOException e) {
e.printStackTrace();
}
}

// Method to read and display content of population file
public static void decodeFiles() {
try {
File populationFile = new File("population.dat");
if (populationFile.exists() && populationFile.isFile()) {
try (RandomAccessFile file = new RandomAccessFile(populationFile, "r")) {
while (file.getFilePointer() < file.length()) {

byte[] nameBytes = new byte[60];
file.readFully(nameBytes);
String name = new String(nameBytes).trim();

int inhabitants = file.readInt();
double rt = file.readDouble();

byte[] postalCodeBytes = new byte[5];
file.readFully(postalCodeBytes);
String postalCode = new String(postalCodeBytes).trim();

// Display read data
System.out.println("Name: " + name);
System.out.println("Inhabitants: " + inhabitants);
System.out.println("RT: " + rt);
System.out.println("Postal Code: " + postalCode);
System.out.println("---------------------------");
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("File population.dat does not exist.");
}
} catch (Exception e) {
e.printStackTrace();
}
}

// Method to modify the fifth population record
public static void modifyFifthPopulationRecord() {
try {
File populationFile = new File("population.dat");
if (populationFile.exists() && populationFile.isFile()) {
try (RandomAccessFile file = new RandomAccessFile(populationFile, "rw")) {
// Exact size of each record (without UTF headers)
long recordSize = 60 + 4 + 8 + 5;

long recordCount = file.length() / recordSize;

if (recordCount < 5) {
System.out.println("File does not contain enough records (at least 5 required)");
return;
}

file.seek(recordSize * 4); // Position of the fifth record

byte[] nameBytes = new byte[60];
file.readFully(nameBytes);
String name = new String(nameBytes).trim();

int inhabitants = file.readInt();
double rt = file.readDouble();

byte[] postalCodeBytes = new byte[5];
file.readFully(postalCodeBytes);
String postalCode = new String(postalCodeBytes).trim();

// Modify values
inhabitants += 100;
rt -= 0.05;

// Overwrite fifth record with modified values
file.seek(recordSize * 4);
file.writeBytes(String.format("%-60s", name));
file.writeInt(inhabitants);
file.writeDouble(rt);
file.writeBytes(String.format("%-5s", postalCode));

System.out.println("Fifth record updated");

} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}

// Method to add a new population or region record
public static void addPopulationOrRegion() {
System.out.println("1.population 2.region");
int option = input.nextInt();

if (option == 1) {
try (RandomAccessFile file = new RandomAccessFile("population.dat", "rw")) {
Scanner scanner = new Scanner(System.in);
System.out.println("---------Enter a population--------");
file.seek(file.length());
System.out.println("Enter name:");
String name = scanner.nextLine();
name = String.format("%-60s", name);

System.out.println("Enter number of inhabitants:");
int inhabitants = scanner.nextInt();

System.out.println("Enter rt:");
double rt = scanner.nextDouble();

scanner.nextLine();

System.out.println("Enter postal code:");
String postalCode = scanner.nextLine();
postalCode = String.format("%-5s", postalCode);

file.writeUTF(name);
file.writeInt(inhabitants);
file.writeDouble(rt);
file.writeUTF(postalCode);

} catch (IOException e) {
e.printStackTrace();
}
} else if (option == 2) {
try (RandomAccessFile file = new RandomAccessFile("region.dat", "rw")) {
System.out.println("---------Enter a region--------");
file.seek(file.length());
System.out.println("Enter name:");
String name = input.nextLine();
name = String.format("%-30s", name);

System.out.println("Enter number of inhabitants:");
int inhabitants = input.nextInt();

System.out.println("Enter rt:");
double rt = input.nextDouble();

input.nextLine();

file.writeUTF(name);
file.writeInt(inhabitants);
file.writeDouble(rt);

} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Invalid option");
}
}
}



Подробнее здесь: https://stackoverflow.com/questions/791 ... using-java

Вернуться в «JAVA»