简体   繁体   中英

Java: FileOutputStream and FileInputStream together on the same file

Do I can open a file (linux character device) for read+write, and use the two classes to implement a dialog like client-server?

Something like this:

File file = new File("/dev/ttyS0");  
FileOutpuStream fo = new FileOutputStream(file)
FileInputStream fi = new FileInputStream(file)

After the above declarations, can I continuously send pollings (questions) to the file, and read its replies? (Of course, attached to ttyS0 there is a kind of server)

I was not able to test it, but you might want to give RandomAccessFile a try. It does not give you the opertunity to create streams, but it implements DataInput and DataOutput. Thats maybe good enough for your purpose? RandomAccessFile docs

String file = "/dev/ttyS0";
try {
    RandomAccessFile f = new RandomAccessFile(file, "rwd");
} catch (IOException e){
    e.printStackTrace();
}

The /dev/ttyS0 file is a device file for a serial terminal.

If the device has been configured appropriately to connect to a serial terminal line, then you should be able to read and write like that. However, on a typical desktop or laptop, it probably won't work because there won't be connected serial line.

(For example, when I do this on my PC:

$ sudo bash -c "cat < /dev/ttyS0"

I get this:

cat: -: Input/output error

which is saying that the device cannot be read from.)

Note that a /dev/tty* device does not behave like a regular file. The characters that are written in no way relate to the characters that you read back. Also note that it is not possible to make ioctl requests using the standard Java APIs. So configuring the terminal driver from Java would be problematic.


If you were talking abour reading and writing a regular file, it should work too. However, the behavior could be a rather confusing, especially if you have buffering in your streams. One issue you need to deal with is that the two file descriptors are independent of each other.

If you need to do this kind of thing with a regular file, you should probably use RandomAccessFile .

我没有尝试过RandomAccessFile,它也可以工作...它可以与FileInputStream和FileOutputStream一起正常工作,请在SO中查看以下答案: https : //stackoverflow.com/a/56935267/7332147

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