Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中对用户I/O使用异常_Java_Exception_Io - Fatal编程技术网

在Java中对用户I/O使用异常

在Java中对用户I/O使用异常,java,exception,io,Java,Exception,Io,我正在尝试做以下工作:我正在用Java编写一个程序,让我可以创建和读取文本文件。到目前为止,我已经能够做到这一点,但困难的(?)部分是:当文本文件中除了A、B或C之外的任何内容都存在时,我必须能够得到一个错误 到目前为止,我得到了: package textfile; import java.io.*; import static java.lang.System.*; class OutWrite { public static void main(String[] args) {

我正在尝试做以下工作:我正在用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!");
    }
  }   
}


有人能帮我指引正确的方向吗?

只要在发现a、B、C以外的新角色时抛出异常即可

使用


谢谢你,我花了好长时间才出去。。。毕竟没那么难!
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");
    }
  }    
}
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");
        }
    }
}