Java保存/打开文件对象 [英] Java saving/opening File objects

查看:137
本文介绍了Java保存/打开文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用原始字节流的会议聊天应用程序中苦苦试图实现TCP文件传输之后,我决定发送通过对象流传输的文件要容易得多。这些文件作为内存中的File对象发送并存储在目的地(不管是中央服务器还是下载客户端)。但是,这些文件没有用,只是文件对象 - 客户端应该能够打开它们。有没有在Java中的方式来保存文件对象作为硬盘文件或甚至打开它们通过Java?


解决方案

什么你的意思是文件对象;你是指 java.io.File



java.io.File 只是目录名称和文件名称的表示。它不是一个可以容纳文件内容的对象。

如果你的数据是在内存中的一个字节数组,那么是的,你可以保存到一个文件:

  byte [] data = ...; 

OutputStream out = new FileOutputStream(new File(C:\\someplace\\filename.dat));
out.write(data);
out.close();

请参阅基本我从甲骨文的Java教程/ O课程学习如何使用的FileInputStream 和读取和写入文件 FileOutputStream


After painstakingly trying to implement TCP file transfer in my conference chat application using raw byte streams, I've decided it's much easier to send files that I want transferred through object streams. The files are sent and stored at their destination (whether that is the central server or the downloading client) as in-memory File objects. However, these files are no use as just File objects - clients should be able to open them. Is there a way in java to save File objects as hard-disk files or to even open them up through Java?

解决方案

What do you mean with "File objects"; do you mean java.io.File?

Class java.io.File is just a representation of a directory name and filename. It is not an object which can hold the contents of a file.

If you have the data in for example a byte array in memory, then yes, you can save that to a file:

byte[] data = ...;

OutputStream out = new FileOutputStream(new File("C:\\someplace\\filename.dat"));
out.write(data);
out.close();

See the Basic I/O Lesson from Oracle's Java Tutorials to learn how to read and write files with a FileInputStream and FileOutputStream.

这篇关于Java保存/打开文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆