Java file Byte character data conversion

Source: Internet
Author: User

Package io;//: Io/buffertotext.java//converting text to and from Bytebuffersimport Java.nio.*;import java.nio.channels. *;import java.nio.charset.*;import java.io.*;/* * Convert data: * buffers contain normal bytes, in order to convert them into characters, either decode them at the time of input, or decode them from the buffer output.  */public class Buffertotext {private static final int bsize = 1024;public static void Main (string[] args) throws Exception {FileChannel FC = new FileOutputStream ("Data2.txt"). Getchannel (); Fc.write (Bytebuffer.wrap ("Some text". GetBytes ())); Fc.close (); FC = new FileInputStream ("Data2.txt"). Getchannel (); Bytebuffer buff = bytebuffer.allocate (bsize); Fc.read (Buff); Buff.flip (); Doesn ' t work:System.out.println (Buff.ascharbuffer ()); Decode using this system ' s default Charset:buff.rewind (); String encoding = System.getproperty ("file.encoding"); SYSTEM.OUT.PRINTLN ("decoded using" + Encoding + ":" + charset.forname (encoding). Decode (buff)); Or, we could encode with something that would PRINT:FC = new FileOutputStream ("Data2.txt"). Getchannel (); Fc.wriTe (Bytebuffer.wrap ("Some text". GetBytes ("Utf-16be")); Fc.close (); Now try reading AGAIN:FC = new FileInputStream ("Data2.txt"). Getchannel (); Buff.clear (); Fc.read (Buff); Buff.flip (); System.out.println (Buff.ascharbuffer ()); Use a charbuffer to write THROUGH:FC = new FileOutputStream ("Data2.txt"). Getchannel (); Buff = Bytebuffer.allocate (24); More than needed Buff.ascharbuffer (). Put ("Some text"); Fc.write (Buff); Fc.close (); Read and DISPLAY:FC = new FileInputStream ("Data2.txt"). Getchannel (); Buff.clear (); Fc.read (Buff); Buff.flip ();  System.out.println (Buff.ascharbuffer ());}}

Java file Byte character data conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.