java - 关于从文本文件中读取单词的问题
问题描述
该程序从现有文件中读取单词,更改它们的顺序并将单词写入同一文件。问题是,它不会从文件中读取单词,并且会立即抛出 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");
}
它抛出底部方法的异常(“文件读取/写入失败。”)
解决方案
推荐阅读
- python - 在 Excel 或 Jupyter 中对范围内的相关矩阵进行排序
- amazon-web-services - 尝试创建 aws_route53_record 以指向负载均衡器,但使用 terraform 不断出现错误
- swift - 在 UIView 上创建曲线
- laravel-8 - 我没有得到 laravel 8 jetstream 个人资料照片路径。它节省了存储空间
- nestjs - 如何从左连接表中选择数据?
- karate - 空手道比赛包含深度无法正常工作
- powershell - 为什么 Get-Services 给我 NetTcpPortSharing 服务的 PermissionDenied?
- scala - 如何为 Map[String, Any] 编写自定义 circe 编解码器
- python - python列表如何管理不同数据类型的值?
- javascript - 我将如何比较表格中的两个日期并验证它们?第二个不应该在第一个之前