簡體   English   中英

FileOutputStream在部分中不起作用

[英]FileOutputStream in parts does not work

我正在嘗試為我的應用程序開發文件傳輸功能。 我對文件傳輸的實現是以對象的形式部分發送文件的,這些對象包含有關文件以及所發送字節的信息。 但是,我注意到,只有將所有接收到的字節保存在列表中,然后立即將其寫入文件中,才能真正寫入文件。 如果我嘗試部分寫入文件,則最終會得到一個空文件,好像根本沒有寫入該文件一樣。

這是我的方法,該方法讀取原始文件,然后分部分發送:

public void sendFile(File src) {
    try {

        BufferedInputStream is = new BufferedInputStream(new FileInputStream(src));
        Message msg = new Message(MType.FILE_OPEN, true);
        com.transmit(msg);
        byte[] buf = new byte[Utility.bufferSize];
        msg = new Message(MType.FILE_NAME, src.getName());
        msg.setValue(MType.FILE_SIZE, Files.size(src.toPath()));
        com.transmit(msg);
        for (int count = is.read(buf); count > 0; count = is.read(buf)) {

            msg = new Message(MType.FILE_NAME, src.getName());
            msg.setValue(MType.FILE_SIZE, Files.size(src.toPath()));
            msg.setValue(MType.FILE_BYTE, buf);
            msg.setValue(MType.FILE_COUNT, count);
            com.transmit(msg);

        }
        msg = new Message(MType.FILE_NAME, src.getName());
        msg.setValue(MType.FILE_SIZE, Files.size(src.toPath()));
        msg.setValue(MType.FILE_CLOSE, true);
        is.close();
        com.transmit(msg);

    } catch (IOException e) {
        sender.getChatRoomController().error(ProgramError.ATTACH_FILE);
        Utility.log(e);
        e.printStackTrace();
    }
}

這是我的另一端接收Message對象的方法:

public void readFile(Message msg) {

    if (msg.hasID(MType.FILE_NAME)) {
        String name = msg.getValue(MType.FILE_NAME).toString();
        long size = (long) msg.getValue(MType.FILE_SIZE);
        File file = new File(Directories.fDir.getDirectory(), name);
        TempFile tf = new TempFile(file);
        if (!map.containsKey(file)) {
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            map.put(file, tf);
        } else {
            tf = map.get(file);
        }
        if (msg.hasValue(MType.FILE_BYTE)) {
            byte[] buf = (byte[]) msg.getValue(MType.FILE_BYTE);
            int count = (int) msg.getValue(MType.FILE_COUNT);
            tf.addEntry(buf, count);
        }
        if (msg.hasValue(MType.FILE_CLOSE)) {
            tf.writeFile(true);
            map.remove(file);

            if (sender instanceof Server) {
                Server server = (Server) sender;
                msg = new Message(MType.FILE_NAME, name);
                msg.setValue(MType.FILE_SIZE, size);
                msg.setValue(MType.FILE_ATTACHMENT, server.getFileID());
                addFile(file, server);
                server.broadcast(msg);
            }

        }
    }
}

這是我的TempFile類:

    public class TempFile {

    private ArrayList<Byte[]> data;
    private ArrayList<Integer> counts;
    private File file;

    public TempFile(File file) {
        data = new ArrayList<>();
        counts = new ArrayList<>();
        this.file = file;
    }

    public void addEntry(byte[] data, int count) {

        this.data.add(Utility.toWrapper(data));
        this.counts.add(count);

    }

    public void writeFile(boolean append) {
        try {
            BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
            for (int i = 0; i < data.size(); i++) {
                byte[] chunk = Utility.toPrimitive(data.get(i));
                int count = counts.get(i);
                os.write(chunk, 0, count);
            }
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

這是我涉及實際臨時文件的其他實現:

    public class TempFile2 {

    private File file;
    private File tempFile;
    private FileOutputStream os;

    public TempFile2(File file) {
        this.file = file;
        this.tempFile = new File(file.getParent(), FilenameUtils.getBaseName(file.getName()) + ".tmp");
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os = new FileOutputStream(tempFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void addEntry(byte[] data, int count) {

        try {
            os.write(data, 0, count);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writeFile() {

        try {
            os.close();
            Files.copy(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

要使此工作正常進行,您需要在運行時刷新輸出流。

    public class TempFile2 {

    private File file;
    private File tempFile;
    private FileOutputStream os;

    public TempFile2(File file) {
        this.file = file;
        this.tempFile = new File(file.getParent(), FilenameUtils.getBaseName(file.getName()) + ".tmp");
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os = new FileOutputStream(tempFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void addEntry(byte[] data, int count) {

        try {
            os.write(data, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writeFile() {

        try {
            os.close();
            Files.copy(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

實際上,除了使輸出流保持打開狀態,您還可以在每次接收到數據塊時將其打開和關閉:

    public class TempFile2 {

    private File file;
    private File tempFile;

    public TempFile2(File file) {
        this.file = file;
        this.tempFile = new File(file.getParent(), FilenameUtils.getBaseName(file.getName()) + ".tmp");
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void addEntry(byte[] data, int count) {
        try(OutputStream os = new FileOutputStream(tempFile, true)) {
            os.write(data, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writeFile() {

        try {
            Files.copy(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

另外,我有一個建議。

read()操作可能只讀取幾個字節,但是您當前的實現將通過任何方式發送整個數組。 一種解決方案是制作一個新的較小的數組來保存數據:

byte[] bytesToSend = new byte[count];
System.arraycopy(buf, 0, bytesToSend, 0, count);

我認為一個更好的解決方案是在這里利用Base64類並發送字節數組的序列化版本,而不是字節數組本身。

// In sender
byte[] bytesToSend = new byte[count];
System.arraycopy(buf, 0, bytesToSend, 0, count);
String encodedBytes = Base64.getEncoder().encodeToString(bytesToSend);
msg.setValue(MType.FILE_BYTE, encodedBytes);

// In receiver
String encodedBytes = (String) msg.getValue(MType.FILE_BYTE);
buf = Base64.getDecoder().decode(encodedBytes);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM