0
public class L20 {
public static void main(String[] args) throws IOException{
    Scanner input=new Scanner(System.in);

    System.out.println("Enter file name");
    String in=input.nextLine();
    try{
        textWriter(in);
        textReader(in);
        textChanger(in);

    }catch(Exception e){

    }

}

public static void textWriter(String path) throws IOException{
    String[] alphabet=    
 {"a","b","c","d","e","f","g","h","i","j","k","m","l","n","o","p","q","r","s","t","u","v","w","x","y","z"};
File file=new File(path);
Writer output=null;
    Random number=new Random();
    output=new BufferedWriter(new FileWriter(file));
    int lines=10+number.nextInt(11);
    for(int i=0;i<lines;i++){
    int it2=1+number.nextInt(9);
    int n1=number.nextInt(26);
    int n2=number.nextInt(26);
    int n3=number.nextInt(26);

    String t2=Integer.toString(it2);
    String t1=alphabet[n1]+alphabet[n2]+alphabet[n3];
    String text=t1+t2;
    output.write(text);
    ((BufferedWriter) output).newLine();
    }
    output.close();
    System.out.println("Your file has been written");
}

public static void textReader(String path) throws IOException{
    File file=new File(path);
    Scanner input;
    input=new Scanner(file);
    String line;
    while((line=input.nextLine())!=null){
        System.out.println(line);
    }
    input.close();
}

private static void textChanger(String path) throws IOException{
    File file=new File(path);
    Scanner input2;
    input2=new Scanner(file);
    String line;
    while((line=input2.nextLine())!=null){
        System.out.println(line);
    }
    input2.close();
}

}

textWriter 工作正常。textReader 和 textChanger 完全一样!但是 textReader 工作正常,而 textChanger 不行!为什么?我什至为每种方法重命名了扫描仪。看来 Text.txt 只能读取一次??

4

1 回答 1

10

问题是您的程序正在默默地崩溃textReader并且textChanger根本没有被调用。而不是这个:

while((line=input.nextLine())!=null){
    System.out.println(line);
}

你应该使用这个:

while(input.hasNextLine()){
    System.out.println(input.nextLine());
}

Scanner.nextLine()null如果没有更多的输入,将不会返回;它会抛出一个NoSuchElementException.

一般来说,不要默默地捕捉异常。至少打电话printStackTrace()或记录问题!

于 2012-11-28T06:07:15.797 回答