简体   繁体   中英

Java Scanner doesn't read

I am trying to download a file that contains an integer from a remote machine, increase the value of the integer locally, write the new value to the same file and upload the file. I use scp. It downloads the file successfully. I use shell file for downloading and uploading processes. But I have problems with Scanner .

Here is the code:

import java.io.*;
import java.util.*;
public class shell {
    public static void main(String[] args) throws IOException{
        Runtime.getRuntime().exec("/home/ayyuce/Desktop/download.sh");
        File f= new File("/home/ayyuce/Desktop/yeni.txt");
        PrintWriter pw = new PrintWriter(f);
        Scanner s= new Scanner(f);
        int num=0;
        if(s.hasNextLine()){
            num=s.nextInt();
        } else {
            System.out.println("Error");
        }
        int increase=num++;
        pw.println(increase);

        Runtime.getRuntime().exec("/home/ayyuce/Desktop/upload.sh");
        s.close();
        pw.close();
    }
}

The output is: Error

I wonder what is the problem with Scanner .

Thank you so much!

PrintWriter pw = new PrintWriter(f);

From javadoc

file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

Of course, Scanner can't read anything, because the file was truncated to zero size in new PrintWriter(f) .

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