首页 > 解决方案 > 关于从文本文件中读取单词的问题

问题描述

该程序从现有文件中读取单词,更改它们的顺序并将单词写入同一文件。问题是,它不会从文件中读取单词,并且会立即抛出 IOE 异常。用户将文件路径写入文件。这里是部分代码,负责文件读取;

import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;

public class WordOrder {
    public ArrayList<ArrayList<String>> LinesList;
    public ArrayList<String> Words_per_line_list;
    protected String FileName;
    public WordOrder(){
        LinesList = new ArrayList<>();
        Words_per_line_list = new ArrayList<>();
    }
    public void wordReading() throws IOException{
        String word_to_be_read;
            Scanner scan = new Scanner (System.in);
            System.out.println ("Enter the path of the file, e.g. D:/Folder/File.txt");
            FileName = scan.nextLine ();
            BufferedReader in = new BufferedReader(new FileReader (FileName));
            if(in.read () == -1){
                throw new IOException ("File does not exist or cannot be accessed");
            }
            System.out.println ("Test");
            int c, i =0;
            while(in.readLine() != null) {
                LinesList.add(i, Words_per_line_list);
                while ((c = in.read ()) != -1) {
                    word_to_be_read = in.readLine ();
                    Words_per_line_list.add(c, word_to_be_read);
                    System.out.println ("Test");
                }
                i++;
            }
            }
}

这是代码,上面的方法被调用

        try {
            wordReading();
            Scanner scan = new Scanner (System.in);
            System.out.println ("Hello, welcome to the WordSwapper. Please choose an operation. Press 1 to swap two lines, press 2 to swap two words within different lines.");
            byte choice = scan.nextByte ();
            scan.nextLine ();
            switch (choice) {
                case (1) -> swapLines ();
                case (2) -> swapWords ();
                default -> System.out.println ("Invalid choice. Please try again");
            }
            wordWriting ();
        } catch (InputMismatchException ie) {
            System.out.println ("Please enter an Integer");
        }catch(IOException ioe){
            System.out.println ("File reading/writing has failed");
        }

它抛出底部方法的异常(“文件读取/写入失败。”)

标签: javafile-ioio

解决方案


推荐阅读