Class IOChannel
- All Implemented Interfaces:
Proxy
GIOChannel data type aims to provide a portable method for
using file descriptors, pipes, and sockets, and integrating them
into the main event loop (see GLib.MainContext). Currently,
full support is available on UNIX platforms; support for Windows
is only partially complete.
To create a new GIOChannel on UNIX systems use
unixNew(int). This works for plain file descriptors,
pipes and sockets. Alternatively, a channel can be created for a
file in a system independent manner using file(java.lang.String, java.lang.String).
Once a GIOChannel has been created, it can be used in a generic
manner with the functions readChars(org.javagi.base.Out<byte[]>, org.javagi.base.Out<java.lang.Long>),
writeChars(byte[], long, org.javagi.base.Out<java.lang.Long>), seekPosition(long, org.gnome.glib.SeekType),
and shutdown(boolean).
To add a GIOChannel to the main event loop, use GLib.ioAddWatch(org.gnome.glib.IOChannel, int, java.util.Set<org.gnome.glib.IOCondition>, org.gnome.glib.IOFunc) or
GLib#ioAddWatchFull. Here you specify which events you are
interested in on the GIOChannel, and provide a function to be called
whenever these events occur.
GIOChannel instances are created with an initial reference count of 1.
ref() and unref() can be used to
increment or decrement the reference count respectively. When the
reference count falls to 0, the GIOChannel is freed. (Though it
isn’t closed automatically, unless it was created using
file(java.lang.String, java.lang.String).) Using GLib.ioAddWatch(org.gnome.glib.IOChannel, int, java.util.Set<org.gnome.glib.IOCondition>, org.gnome.glib.IOFunc) or
GLib#ioAddWatchFull increments a channel’s reference count.
The new functions readChars(org.javagi.base.Out<byte[]>, org.javagi.base.Out<java.lang.Long>),
readLine(org.javagi.base.Out<java.lang.String>, org.javagi.base.Out<java.lang.Long>, org.javagi.base.Out<java.lang.Long>), readLineString(java.lang.String, java.lang.foreign.MemorySegment),
readToEnd(org.javagi.base.Out<byte[]>), writeChars(byte[], long, org.javagi.base.Out<java.lang.Long>),
seekPosition(long, org.gnome.glib.SeekType), and flush()
should not be mixed with the deprecated functions
read(java.lang.String, long, java.lang.foreign.MemorySegment), write(java.lang.String, long, java.lang.foreign.MemorySegment), and
seek(long, org.gnome.glib.SeekType) on the same channel.
-
Constructor Summary
ConstructorsConstructorDescriptionIOChannel(MemorySegment address) Create a IOChannel proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Deprecated.Use g_io_channel_shutdown() instead.static IOChannelErrorerrorFromErrno(int en) Converts anerrnoerror number to aGIOChannelError.static Quarkstatic IOChannelOpen a filefilenameas aGIOChannelusing modemode.This channel will be closed when the last reference to it is dropped, so there is no need to call g_io_channel_close() (though doing so will not cause problems, as long as no attempt is made to access the channel after it is closed).flush()Flushes the write buffer for the GIOChannel.This function returns aGIOConditiondepending on whether there is data to be read/space to write data in the internal buffers in theGIOChannel.booleanReturns whether this IOChannel is buffered.longGets the buffer size.booleanReturns whether the file/socket/whatever associated with this IOChannel will be closed when this IOChannel receives its final unref and is destroyed.Gets the encoding for the input/output of the channel.getFlags()Gets the current flags for aGIOChannel, including read-only flags such asIOFlags.IS_READABLE.getLineTerm(@Nullable Out<Integer> length) This returns the string thatGIOChanneluses to determine where in the file a line break occurs.static @Nullable TypegetType()Get the GType of the IOChannel classvoidinit()Initializes aGIOChannelstruct.read(String buf, long count, MemorySegment bytesRead) Deprecated.Use g_io_channel_read_chars() instead.Replacement for g_io_channel_read() with the new API.Reads a line, including the terminating character(s), from aGIOChannelinto a newly-allocated string.readLineString(String buffer, @Nullable MemorySegment terminatorPos) Reads a line from aGIOChannel, using aGStringas a buffer.Reads all the remaining data from the file.readUnichar(Out<Integer> thechar) Reads a Unicode character fromchannel.This function cannot be called on a channel withnullencoding.ref()Increments the reference count of aGIOChannel.Deprecated.Use g_io_channel_seek_position() instead.seekPosition(long offset, SeekType type) Replacement for g_io_channel_seek() with the new API.voidsetBuffered(boolean buffered) The buffering state can only be set if the channel's encoding isnull.voidsetBufferSize(long size) Sets the buffer size.voidsetCloseOnUnref(boolean doClose) Whether to close the channel on the final unref of theGIOChanneldata structure.setEncoding(@Nullable String encoding) Sets the encoding for the input/output of the channel.Sets the (writeable) flags in this IOChannel to (flags&IOFlags.SET_MASK).Sets the (writeable) flags in this IOChannel to (flags&IOFlags.SET_MASK).voidsetLineTerm(@Nullable String lineTerm, int length) This sets the string thatGIOChanneluses to determine where in the file a line break occurs.shutdown(boolean flush) Close an IO channel.intReturns the file descriptor of theGIOChannel.static IOChannelunixNew(int fd) Creates a newGIOChannelgiven a file descriptor.voidunref()Decrements the reference count of aGIOChannel.intvoidwin32MakePollfd(Set<IOCondition> condition, PollFD fd) voidwin32MakePollfd(IOCondition condition, PollFD fd) static IOChannelwin32NewFd(int fd) Creates a newGIOChannelgiven a file descriptor on Windows.static IOChannelwin32NewMessages(long hwnd) Creates a newGIOChannelgiven a window handle on Windows.static IOChannelwin32NewSocket(int socket) Creates a newGIOChannelgiven a socket on Windows.static IOChannelwin32NewStreamSocket(int socket) static intvoidwin32SetDebug(boolean flag) write(String buf, long count, MemorySegment bytesWritten) Deprecated.Use g_io_channel_write_chars() instead.writeChars(@org.jspecify.annotations.Nullable byte @Nullable [] buf, long count, Out<Long> bytesWritten) Replacement for g_io_channel_write() with the new API.writeUnichar(int thechar) Writes a Unicode character tochannel.This function cannot be called on a channel withnullencoding.Methods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
IOChannel
Create a IOChannel proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
-
Method Details
-
getType
-
file
Open a filefilenameas aGIOChannelusing modemode.This channel will be closed when the last reference to it is dropped, so there is no need to call g_io_channel_close() (though doing so will not cause problems, as long as no attempt is made to access the channel after it is closed).- Parameters:
filename- A string containing the name of a filemode- One of "r", "w", "a", "r+", "w+", "a+". These have the same meaning as in fopen()- Returns:
- A
GIOChannelon success,nullon failure. - Throws:
GErrorException- seeGError
-
unixNew
Creates a newGIOChannelgiven a file descriptor. On UNIX systems this works for plain files, pipes, and sockets.The returned
GIOChannelhas a reference count of 1.The default encoding for
GIOChannelis UTF-8. If your application is reading output from a command using via pipe, you may need to set the encoding to the encoding of the current locale (see g_get_charset()) with the g_io_channel_set_encoding() function. By default, the fd passed will not be closed when the final reference to theGIOChanneldata structure is dropped.If you want to read raw binary data without interpretation, then call the g_io_channel_set_encoding() function with
nullfor the encoding argument.This function is available in GLib on Windows, too, but you should avoid using it on Windows. The domain of file descriptors and sockets overlap. There is no way for GLib to know which one you mean in case the argument you pass to this function happens to be both a valid file descriptor and socket. If that happens a warning is issued, and GLib assumes that it is the file descriptor you mean.
- Parameters:
fd- a file descriptor.- Returns:
- a new
GIOChannel.
-
win32NewFd
Creates a newGIOChannelgiven a file descriptor on Windows. This works for file descriptors from the C runtime.This function works for file descriptors as returned by the open(), creat(), pipe() and fileno() calls in the Microsoft C runtime. In order to meaningfully use this function your code should use the same C runtime as GLib uses, which is msvcrt.dll. Note that in current Microsoft compilers it is near impossible to convince it to build code that would use msvcrt.dll. The last Microsoft compiler version that supported using msvcrt.dll as the C runtime was version 6. The GNU compiler and toolchain for Windows, also known as Mingw, fully supports msvcrt.dll.
If you have created a
GIOChannelfor a file descriptor and started watching (polling) it, you shouldn't call read() on the file descriptor. This is because adding polling for a file descriptor is implemented in GLib on Windows by starting a thread that sits blocked in a read() from the file descriptor most of the time. All reads from the file descriptor should be done by this internal GLib thread. Your code should call only g_io_channel_read().This function is available only in GLib on Windows.
- Parameters:
fd- a C library file descriptor.- Returns:
- a new
GIOChannel.
-
win32NewMessages
Creates a newGIOChannelgiven a window handle on Windows.This function creates a
GIOChannelthat can be used to poll for Windows messages for the window in question.- Parameters:
hwnd- a window handle.- Returns:
- a new
GIOChannel.
-
win32NewSocket
Creates a newGIOChannelgiven a socket on Windows.This function works for sockets created by Winsock. It's available only in GLib on Windows.
Polling a
GSourcecreated to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.- Parameters:
socket- a Winsock socket- Returns:
- a new
GIOChannel
-
win32NewStreamSocket
-
errorFromErrno
Converts anerrnoerror number to aGIOChannelError.- Parameters:
en- anerrnoerror number, e.g.EINVAL- Returns:
- a
GIOChannelErrorerror number, e.g.IOChannelError.INVAL.
-
errorQuark
-
win32Poll
-
close
Deprecated.Use g_io_channel_shutdown() instead.Close an IO channel. Any pending data to be written will be flushed, ignoring errors. The channel will not be freed until the last reference is dropped using g_io_channel_unref(). -
flush
Flushes the write buffer for the GIOChannel.- Returns:
- the status of the operation: One of
IOStatus.NORMAL,IOStatus.AGAIN, orIOStatus.ERROR. - Throws:
GErrorException- seeGError
-
getBufferCondition
This function returns aGIOConditiondepending on whether there is data to be read/space to write data in the internal buffers in theGIOChannel. Only the flagsIOCondition.INandIOCondition.OUTmay be set.- Returns:
- A
GIOCondition
-
getBufferSize
public long getBufferSize()Gets the buffer size.- Returns:
- the size of the buffer.
-
getBuffered
public boolean getBuffered()Returns whether this IOChannel is buffered.- Returns:
trueif the this IOChannel is buffered.
-
getCloseOnUnref
public boolean getCloseOnUnref()Returns whether the file/socket/whatever associated with this IOChannel will be closed when this IOChannel receives its final unref and is destroyed. The default value of this istruefor channels created by g_io_channel_new_file (), andfalsefor all other channels.- Returns:
trueif the channel will be closed,falseotherwise.
-
getEncoding
Gets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The encodingnullmakes the channel safe for binary data.- Returns:
- A string containing the encoding, this string is owned by GLib and must not be freed.
-
getFlags
Gets the current flags for aGIOChannel, including read-only flags such asIOFlags.IS_READABLE.The values of the flags
IOFlags.IS_READABLEandIOFlags.IS_WRITABLEare cached for internal use by the channel when it is created. If they should change at some later point (e.g. partial shutdown of a socket with the UNIX shutdown() function), the user should immediately call g_io_channel_get_flags() to update the internal values of these flags.- Returns:
- the flags which are set on the channel
-
getLineTerm
This returns the string thatGIOChanneluses to determine where in the file a line break occurs. A value ofnullindicates autodetection. Since 2.84, the return value is always nul-terminated.- Parameters:
length- a location to return the length of the line terminator- Returns:
- The line termination string. This value is owned by GLib and must not be freed.
-
init
public void init()Initializes aGIOChannelstruct.This is called by each of the above functions when creating a
GIOChannel, and so is not often needed by the application programmer (unless you are creating a new type ofGIOChannel). -
read
Deprecated.Use g_io_channel_read_chars() instead.Reads data from aGIOChannel.- Parameters:
buf- a buffer to read the data into (which should be at least count bytes long)count- the number of bytes to read from theGIOChannelbytesRead- returns the number of bytes actually read- Returns:
IOError.NONEif the operation was successful.
-
readChars
public IOStatus readChars(@Nullable Out<byte[]> buf, @Nullable Out<Long> bytesRead) throws GErrorException Replacement for g_io_channel_read() with the new API.- Parameters:
buf- a buffer to read data intobytesRead- The number of bytes read. This may be zero even on success if count < 6 and the channel's encoding is non-null. This indicates that the next UTF-8 character is too wide for the buffer.- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
readLine
public IOStatus readLine(Out<String> strReturn, @Nullable Out<Long> length, @Nullable Out<Long> terminatorPos) throws GErrorException Reads a line, including the terminating character(s), from aGIOChannelinto a newly-allocated string.strReturnwill contain allocated memory if the return isIOStatus.NORMAL.- Parameters:
strReturn- The line read from theGIOChannel, including the line terminator. This data should be freed with g_free() when no longer needed. This is a nul-terminated string. If alengthof zero is returned, this will benullinstead.length- location to store length of the read data, ornullterminatorPos- location to store position of line terminator, ornull- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
readLineString
public IOStatus readLineString(String buffer, @Nullable MemorySegment terminatorPos) throws GErrorException Reads a line from aGIOChannel, using aGStringas a buffer.- Parameters:
buffer- aGStringinto which the line will be written. Ifbufferalready contains data, the old data will be overwritten.terminatorPos- location to store position of line terminator, ornull- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
readToEnd
Reads all the remaining data from the file.- Parameters:
strReturn- Location to store a pointer to a string holding the remaining data in theGIOChannel. This data should be freed with g_free() when no longer needed. This data is terminated by an extra nul character, but there may be other nuls in the intervening data.- Returns:
IOStatus.NORMALon success. This function never returnsIOStatus.EOF.- Throws:
GErrorException- seeGError
-
readUnichar
Reads a Unicode character fromchannel.This function cannot be called on a channel withnullencoding.- Parameters:
thechar- a location to return a character- Returns:
- a
GIOStatus - Throws:
GErrorException- seeGError
-
ref
Increments the reference count of aGIOChannel.- Returns:
- the this IOChannel that was passed in (since 2.6)
-
seek
Deprecated.Use g_io_channel_seek_position() instead.Sets the current position in theGIOChannel, similar to the standard library function fseek().- Parameters:
offset- an offset, in bytes, which is added to the position specified bytypetype- the position in the file, which can beSeekType.CUR(the current position),SeekType.SET(the start of the file), orSeekType.END(the end of the file)- Returns:
IOError.NONEif the operation was successful.
-
seekPosition
Replacement for g_io_channel_seek() with the new API.- Parameters:
offset- The offset in bytes from the position specified bytypetype- aGSeekType. The typeSeekType.CURis only allowed in those cases where a call to g_io_channel_set_encoding () is allowed. See the documentation for g_io_channel_set_encoding () for details.- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
setBufferSize
public void setBufferSize(long size) Sets the buffer size.- Parameters:
size- the size of the buffer, or 0 to let GLib pick a good size
-
setBuffered
public void setBuffered(boolean buffered) The buffering state can only be set if the channel's encoding isnull. For any other encoding, the channel must be buffered.A buffered channel can only be set unbuffered if the channel's internal buffers have been flushed. Newly created channels or channels which have returned
IOStatus.EOFnot require such a flush. For write-only channels, a call to g_io_channel_flush () is sufficient. For all other channels, the buffers may be flushed by a call to g_io_channel_seek_position (). This includes the possibility of seeking with seek typeSeekType.CURand an offset of zero. Note that this means that socket-based channels cannot be set unbuffered once they have had data read from them.On unbuffered channels, it is safe to mix read and write calls from the new and old APIs, if this is necessary for maintaining old code.
The default state of the channel is buffered.
- Parameters:
buffered- whether to set the channel buffered or unbuffered
-
setCloseOnUnref
public void setCloseOnUnref(boolean doClose) Whether to close the channel on the final unref of theGIOChanneldata structure. The default value of this istruefor channels created by g_io_channel_new_file (), andfalsefor all other channels.Setting this flag to
truefor a channel you have already closed can cause problems when the final reference to theGIOChannelis dropped.- Parameters:
doClose- Whether to close the channel on the final unref of the GIOChannel data structure.
-
setEncoding
Sets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The default encoding for the external file is UTF-8.The encoding
nullis safe to use with binary data.The encoding can only be set if one of the following conditions is true:
- The channel was just created, and has not been written to or read from yet.
- The channel is write-only.
- The channel is a file, and the file pointer was just repositioned by a call to g_io_channel_seek_position(). (This flushes all the internal buffers.)
- The current encoding is
nullor UTF-8.
- One of the (new API) read functions has just returned
IOStatus.EOF(or, in the case of g_io_channel_read_to_end(),IOStatus.NORMAL).
- One of the functions g_io_channel_read_chars() or
g_io_channel_read_unichar() has returned
IOStatus.AGAINorIOStatus.ERROR. This may be useful in the case ofConvertError.ILLEGAL_SEQUENCE. Returning one of these statuses from g_io_channel_read_line(), g_io_channel_read_line_string(), or g_io_channel_read_to_end() does not guarantee that the encoding can be changed.
Channels which do not meet one of the above conditions cannot call g_io_channel_seek_position() with an offset of
SeekType.CUR, and, if they are "seekable", cannot call g_io_channel_write_chars() after calling one of the API "read" functions.- Parameters:
encoding- the encoding type- Returns:
IOStatus.NORMALif the encoding was successfully set- Throws:
GErrorException- seeGError
-
setFlags
Sets the (writeable) flags in this IOChannel to (flags&IOFlags.SET_MASK).- Parameters:
flags- the flags to set on the IO channel- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
setFlags
Sets the (writeable) flags in this IOChannel to (flags&IOFlags.SET_MASK).- Parameters:
flags- the flags to set on the IO channel- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
setLineTerm
This sets the string thatGIOChanneluses to determine where in the file a line break occurs.- Parameters:
lineTerm- The line termination string. Usenullfor autodetect. Autodetection breaks on "\\n", "\\r\\n", "\\r", "\\0", and the Unicode paragraph separator. Autodetection should not be used for anything other than file-based channels.length- The length of the termination string. If -1 is passed, the string is assumed to be nul-terminated. This option allows termination strings with embedded nuls.
-
shutdown
Close an IO channel. Any pending data to be written will be flushed ifflushistrue. The channel will not be freed until the last reference is dropped using g_io_channel_unref().- Parameters:
flush- iftrue, flush pending- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
unixGetFd
public int unixGetFd()Returns the file descriptor of theGIOChannel.On Windows this function returns the file descriptor or socket of the
GIOChannel.- Returns:
- the file descriptor of the
GIOChannel.
-
unref
public void unref()Decrements the reference count of aGIOChannel. -
write
Deprecated.Use g_io_channel_write_chars() instead.Writes data to aGIOChannel.- Parameters:
buf- the buffer containing the data to writecount- the number of bytes to writebytesWritten- the number of bytes actually written- Returns:
IOError.NONEif the operation was successful.
-
writeChars
public IOStatus writeChars(@org.jspecify.annotations.Nullable byte @Nullable [] buf, long count, Out<Long> bytesWritten) throws GErrorException Replacement for g_io_channel_write() with the new API.On seekable channels with encodings other than
nullor UTF-8, generic mixing of reading and writing is not allowed. A call to g_io_channel_write_chars () may only be made on a channel from which data has been read in the cases described in the documentation for g_io_channel_set_encoding ().- Parameters:
buf- a buffer to write data fromcount- the size of the buffer. If -1, the buffer is taken to be a nul-terminated string.bytesWritten- The number of bytes written. This can be nonzero even if the return value is notIOStatus.NORMAL. If the return value isIOStatus.NORMALand the channel is blocking, this will always be equal tocountifcount>= 0.- Returns:
- the status of the operation.
- Throws:
GErrorException- seeGError
-
writeUnichar
Writes a Unicode character tochannel.This function cannot be called on a channel withnullencoding.- Parameters:
thechar- a character- Returns:
- a
GIOStatus - Throws:
GErrorException- seeGError
-
win32GetFd
public int win32GetFd() -
win32MakePollfd
-
win32MakePollfd
-
win32SetDebug
public void win32SetDebug(boolean flag)
-