java—关于从文本文件中读取单词的问题

polhcujo  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(247)

该程序从现有文件中读取单词,更改其顺序并将单词写入同一文件。问题是,它不会从文件中读取单词,并且会立即抛出一个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");
        }

它抛出bottom方法的异常(“文件读/写失败”)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题