简体   繁体   中英

JAVA- problem with writing in a file but the program wont finish

import java.util.*;
import java.io.*;

public class CopyFile {
    static Scanner sc = new Scanner(System.in);
    public static void main (String[] args) throws IOException{
        File fin = new File("");
        File fout = new File("");
        // nome dos ficheiros de entrada e saida
        if(args.length==1){
            fin = new File(args[0]);
            System.out.print("Ficheiro de saida: ");
            fout = new File(sc.nextLine());
        }else if(args.length==2){
            fin = new File(args[0]);
            fout = new File(args[1]);
        }else if(args.length==0){
            System.out.print("Ficheiro de entrada: ");
            fin = new File(sc.nextLine());
            System.out.print("Ficheiro de saida: ");
            fout = new File(sc.nextLine());
        }
        // condiçoes do ficheiro de entrada
        do{
            if(fin.exists()==false){
                System.out.print("O ficheiro de entrada não existe, volte a introduzir um novo ficheiro: ");
                fin = new File(sc.nextLine());
            }else if(fin.canRead()==false){
                System.out.print("O ficheiro de entrada nao pode ser lido, volte a introduzir um novo ficheiro: ");
                fin = new File(sc.nextLine());
            }
        }while(fin.exists()==false);
        // condiçoes do ficheiro de saida
        do{
            if(fout.canWrite()==false){
                System.out.print("O ficheiro de saida nao pode ser modificado, volte a introduzir um novo ficheiro: ");
                fout = new File(sc.nextLine());
            }
        }while(fout.canWrite()==false);

        Scanner scf = new Scanner (fin); //para o ficheiro de entrada ser lido
        PrintWriter pw = new PrintWriter(fout); // para o escrever sobre o ficheiro de saida

        do{
            pw.println(scf.hasNextLine());
        }while(scf.hasNextLine()==true);

        scf.close();
        pw.close();
    }
}

I have a question here because what is before this happen normally.I only ask for files and after I input the last file it looks like they want more something write and i dont k why, and the program dont finish. The file i considered was one with nothing(the file out) and one with things writed like(file in)

ASDASd
sdfsdfs
fqgqerqe
erqertq
do{
    pw.println(scf.hasNextLine());
}while(scf.hasNextLine()==true);

You never advance that scanner - you just keep querying hasNextLine() , which will return true infinitely. It seems like you meant to write nextLine() to the output:

do {
    pw.println(scf.nextLine()); // Here
} while (scf.hasNextLine()); // Note, BTW, that the "== true" is redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM