首页 > 解决方案 > Why it says the file is empty?

问题描述

I have a method that writes integer array into a file. When I read it with a method that brings those ints as array it's working. But when I try to count how many ints it says it's empty.

The same code is written on other computer systems. and it's working for him, the SAME code!

I already put the "buffer" byte array into the read method. still not working

File file = new File("/home/arad/Desktop/intFile.bin");
int[] arr = {1,2,3,4,5,6};
//exampleWriteIntegerArray(arr, file);
reverseThisFile(file);

static void reverseThisFile(File file){

    File newFile = new File("/home/arad/Desktop/newIntegerFile.bin");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    int counter = 0;
    System.out.println(file.length());
    try {
        inputStream = new FileInputStream(file);
        outputStream = new FileOutputStream(file);
        byte[] buffer  = new byte[4];
        int actuallyRead;
        while((actuallyRead = inputStream.read()) != -1){
            counter++;``
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println(counter);
}

标签: javafile

解决方案


Is something wrong in lines (input and output files are same):

inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file); //comment this line

Name your variables better (outputFile, inputFile)... Also output stream outputStream is not closed... Try first just to print on console, ...


推荐阅读