Файл произвольного доступа, похоже, переключается с UTF-16 BE на UTF-16 LE после того, как я запустил код для «удаления» данных из файла - PullRequest
1 голос
/ 30 сентября 2019

У меня есть этот проект для Java-класса, где я должен создать файл произвольного доступа, который может содержать данные и что-то делать с данными. Однако я столкнулся с проблемой, когда «удаление» фрагмента данных (замена всех связанных с ним строк на «ПРОБЕЛ») переключает кодировку с UTF-16 BE на LE. Где я ошибся и как я могу это решить?

Я довольно неопытен, когда дело доходит до кодирования, и все, что я пытался сделать, это сделать пробел в нижнем регистре и изменить слово на "пробел"

К сожалению, из-за моей неопытности, мой код такой беспорядок, что я не знаю, как дать минимум. Я извиняюсь за то, что вставляю здесь почти весь файл.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CS1181Project01Wheeler {

    public static void main(String[] args) {
        //main RAF where data is stored
        RandomAccessFile data=null;
        try {
            //creation of file/loading file
            data=new RandomAccessFile("data.dat", "rw");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("this shouldn't be possible");
        }
        //scanner to scan user input
        Scanner userInput=new Scanner(System.in);
        boolean finished=false;
        System.out.println("Welcome to Project01 random access file reader.");
        //the "main menu"/user interface
        while(!finished){
            System.out.println("Please select what you want to do:");
            System.out.println("1. add a film");
            System.out.println("2. remove a film");
            System.out.println("3. find a film");
            System.out.println("4. get stats on all films in this list");
            System.out.println("5. about");
            System.out.println("6. quit");
            int choice=userInput.nextInt();
            userInput.nextLine();
            //adding a film
            if(choice==1){
                System.out.println("please enter the title of the film you would like to add");
                String title=userInput.nextLine();
                String space=null;
                boolean done=false;
                while(!done){
                    try {
                        space=data.readLine();
                        if(space=="SPACE"){
                            data.writeChars(title+"\n");
                            done=true;
                        }
                        if(data.getFilePointer()>=data.length()){
                            data.seek(data.length());
                            data.writeChars(title+"\n");
                            done=true;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
                System.out.println("How long is the film in minutes?");
                int length=userInput.nextInt();
                userInput.nextLine();
                //the code for adding the line repeats itself for each question related to the film
                done=false;
                while(!done){
                    try {
                        space=data.readLine();
                        if(space=="SPACE"){
                            data.writeChars(length+"\n");
                            done=true;
                        }
                        if(data.getFilePointer()>=data.length()){
                            data.seek(data.length());
                            data.writeChars(length+"\n");
                            done=true;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }     
                System.out.println("Who is the biggest actor in the film?");
                String actor=userInput.nextLine();
                done=false;
                while(!done){
                    try {
                        space=data.readLine();
                        if(space=="SPACE"){
                            data.writeChars(actor+"\n");
                            done=true;
                        }
                        if(data.getFilePointer()>=data.length()){
                            data.seek(data.length());
                            data.writeChars(actor+"\n");
                            done=true;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                } 
                System.out.println("What year did it release in?");
                int year=userInput.nextInt();
                userInput.nextLine();
                done=false;
                while(!done){
                    try {
                        space=data.readLine();
                        if(space=="SPACE"){
                            data.writeChars(year+"\n");
                            done=true;
                        }
                        if(data.getFilePointer()>=data.length()){
                            data.seek(data.length());
                            data.writeChars(year+"\n");
                            done=true;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
                System.out.println("What is the height of the biggest actor in cm?");
                int height=userInput.nextInt();
                userInput.nextLine();
                done=false;
                while(!done){
                    try {
                        space=data.readLine();
                        if(space=="SPACE"){
                            data.writeChars(height+"\n");
                            done=true;
                        }
                        if(data.getFilePointer()>=data.length()){
                            data.seek(data.length());
                            data.writeChars(height+"\n");
                            done=true;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }
                System.out.println("how was the film received (poor/mixed/good)?");
                done=false;
                String reception = null;
                while(!done){
                    reception=userInput.nextLine();
                    if("poor".equals(reception) || "mixed".equals(reception) || "good".equals(reception)){
                        done=true;
                    }
                    else{
                        System.out.println("Please enter poor, mixed, or good for the reception");
                    }
                }
                done=false;
                while(!done){
                    try {
                        space=data.readLine();
                        if(space=="SPACE"){
                            data.writeChars(reception+"\n");
                            done=true;
                        }
                        if(data.getFilePointer()>=data.length()){
                            data.seek(data.length());
                            data.writeChars(reception+"\n");
                            done=true;
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                        break;
                    }
                }        
                System.out.println("film added");

            }
            //removing a film
            if(choice==2){
                System.out.println("What's the name of the film you want deleted?");
                String title=userInput.nextLine();
                try {
                    data.seek(0);
                } catch (IOException ex) {
                    Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                }
                boolean answer=false;
                int titleAmount=0;
                long backtrack=0;
                char test=0;
                //goes through the whole file to find where the film is located
                while(!answer){
                    try {
                        System.out.println(data.getFilePointer());
                        test=data.readChar();
                    } catch (IOException ex) {
                        System.out.println("film does not exist");
                        break;
                    }
                    //what the code does if a letter matches the film's title
                    if(test==title.charAt(titleAmount)){
                        if(titleAmount==0){
                            try {
                                backtrack=data.getFilePointer()-1;
                            } catch (IOException ex) {
                                Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        titleAmount+=1;
                        if(titleAmount==title.length()){
                            answer=true;
                            System.out.println("move found");
                        }
                    }
                    else{
                        backtrack=0;
                        titleAmount=0;
                    }
                }
                try {
                    data.seek(backtrack);
                } catch (IOException ex) {
                    Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                }
                for(int i=0; i<6; i++){
                    try {
                        System.out.println(data.getFilePointer());
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        data.writeChars("spaced"+"\n");
                    } catch (IOException ex) {
                        Logger.getLogger(CS1181Project01Wheeler.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

1 Ответ

1 голос
/ 30 сентября 2019

RandomAccessFile методы writeChar и writeChars не утверждают, что они пишут UTF-16, но они эффективно делают, так как символы Java находятся в UTF-16. writeChar всегда записывает старший байт первым, что эквивалентно UTF-16BE .

Из Javadoc :

Записывает {@code char} в файл в виде двухбайтового значения, старший байт сначала . Запись начинается с текущей позиции указателя файла.

(выделение добавлено)

...