【问题标题】:Using exceptions in Java with user I/O在 Java 中通过用户 I/O 使用异常
【发布时间】:2014-03-22 21:13:59
【问题描述】:

我正在尝试执行以下操作:我正在用 Java 制作一个程序,它可以让我创建和读取文本文件。到目前为止,我已经能够做到这一点,但困难(?)部分是这样的:当文本文件中除了 A、B 或 C 之外的任何其他内容时,我必须能够得到错误。

到目前为止,我得到了:

package textfile;

import java.io.*;
import static java.lang.System.*;

class OutWrite {

public static void main(String[] args) {
    try{
        FileWriter fw = new FileWriter("FAS.txt");
        PrintWriter pw = new PrintWriter(fw);

        pw.println("A");
        pw.println("B");
        pw.println("C");

        pw.close();
    } catch (IOException e){
        out.println("ERROR!");
    }
  }   
}

package textfile;

import java.io.*;
import static java.lang.System.*;

class InRead {

public static void main(String[] args) {
    try {
        FileReader fr = new FileReader("FSA.txt");
        BufferedReader br = new BufferedReader(fr);

        String str;
        while ((str = br.readLine()) != null){
            out.println(str);
        }

        br.close();
    } catch (IOException e) {
        out.println("File not found");
    }
  }    
}

谁能指引我正确的方向?

【问题讨论】:

    标签: java exception io


    【解决方案1】:

    当发现 A,B,C 以外的新字符时抛出异常。

    使用,

    class InRead {
    
        public static void main(String[] args) {
            try {
                FileReader fr = new FileReader("FSA.txt");
                BufferedReader br = new BufferedReader(fr);
    
                String str;
                while ((str = br.readLine()) != null) {
                    if (str.equals("A") || str.equals("B") || str.equals("c")) //compare
                        out.println(str);
                    else
                        throw new Exception(); //throw exception
                }
    
                br.close();
            } catch (IOException e) {
                out.println("File not found");
            }
    
            catch (Exception e) {//catch it here and print the req message
                System.out.println("New Character Found");
            }
        }
    }
    

    【讨论】:

    • 谢谢,我花了很长时间才弄清楚...毕竟没那么难!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2015-01-17
    • 2013-06-19
    • 1970-01-01
    • 2014-06-29
    • 2016-09-29
    • 2013-01-30
    相关资源
    最近更新 更多