Java Code Examples for java.nio.charset.Charset#newEncoder()

The following examples show how to use java.nio.charset.Charset#newEncoder() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ToolBarCode.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
     * 生成带logo的二维码
     *
     * @param content  条码文本内容
     * @param width    条码宽度
     * @param height   条码高度
     * @param logoPath 条码中logo的路径
     * @param fileType 文件类型,如png
     * @param savePath 保存路径
     */
    public static void encodeLogo(String content, int width, int height, String logoPath, String fileType, String savePath) throws IOException, WriterException {
        Charset charset = Charset.forName("UTF-8");
        CharsetEncoder encoder = charset.newEncoder();

        byte[] b = encoder.encode(CharBuffer.wrap(content)).array();
        String data = new String(b, "iso8859-1");

        Writer writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(data, QR_CODE, width, height);
        MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.BLACK, 10);
        MatrixToImageWriterEx.writeToFile(matrix, fileType, savePath, logoPath, logoConfig);


//        BitMatrix matrix = MatrixToImageWriterEx.createQRCode(content, width, height);
//        MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.BLUE, 4);
//        MatrixToImageWriterEx.writeToFile(matrix, fileType, savePath, logoPath, logoConfig);
    }
 
Example 2
Source File: _Private_Utils.java    From ion-java with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes a String into bytes of a given encoding.
 * <p>
 * This method is preferred to {@link Charset#encode(String)} and
 * {@link String#getBytes(String)} (<em>etc.</em>)
 * since those methods will replace or ignore bad input, and here we throw
 * an exception.
 *
 * @param s the string to encode.
 *
 * @return the encoded string, not null.
 *
 * @throws IonException if there's a {@link CharacterCodingException}.
 */
public static byte[] encode(String s, Charset charset)
{
    CharsetEncoder encoder = charset.newEncoder();
    try
    {
        ByteBuffer buffer = encoder.encode(CharBuffer.wrap(s));
        byte[] bytes = buffer.array();

        // Make another copy iff there's garbage after the limit.
        int limit = buffer.limit();
        if (limit < bytes.length)
        {
            bytes = copyOf(bytes, limit);
        }

        return bytes;
    }
    catch (CharacterCodingException e)
    {
        throw new IonException("Invalid string data", e);
    }
}
 
Example 3
Source File: JavaCodePageFactory.java    From tn5250j with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param encoding
 * @return A new {@link CodePage} object OR null, if not available.
 */
/* package */ static ICodePage getCodePage(final String encoding) {
	CharsetDecoder dec = null;
	CharsetEncoder enc = null;
	try {
		final Charset cs = java.nio.charset.Charset.forName(encoding);
		dec = cs.newDecoder();
		enc = cs.newEncoder();
	} catch (Exception e) {
		enc = null;
		dec = null;
	}
	if ((enc != null) && (dec != null)) {
		return new JavaCodePageFactory(encoding, enc, dec);
	}
	return null;
}
 
Example 4
Source File: IppUtil.java    From cups4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param str
 * @param charsetName
 * @return
 * @throws CharacterCodingException
 */
static public String getTranslatedString(String str, String charsetName) throws CharacterCodingException {
  if (charsetName == null) {
    charsetName = DEFAULT_CHARSET;
  }
  Charset charset = Charset.forName(charsetName);
  CharsetDecoder decoder = charset.newDecoder();
  CharsetEncoder encoder = charset.newEncoder();
  decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  // Convert a string to charsetName bytes in a ByteBuffer
  // The new ByteBuffer is ready to be read.
  ByteBuffer buf = encoder.encode(CharBuffer.wrap(str));
  // Convert charsetName bytes in a ByteBuffer to a character ByteBuffer
  // and then to a string. The new ByteBuffer is ready to be read.
  CharBuffer cbuf = decoder.decode(buf);
  return cbuf.toString();
}
 
Example 5
Source File: XMLWriter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public XMLWriter(OutputStream os, String encoding, Charset cs) throws XMLStreamException {
    _encoder = cs.newEncoder();
    try {
        _writer = getWriter(os, encoding, cs);
    } catch (UnsupportedEncodingException ex) {
        throw new XMLStreamException(ex);
    }

}
 
Example 6
Source File: FileUtils.java    From MyTv with Apache License 2.0 5 votes vote down vote up
/**
 * 以指定编码读入本地文件,以指定编码方式输出,NIO
 * 
 * @param filePath
 *            文件路径
 * @param inCharsetName
 *            编码名称,读入
 * @param outCharsetName
 *            编码名称,输出
 * @throws FileNotFoundException
 * @throws IOException
 * @return
 */
public static byte[] readWithNIO(String filePath, String inCharsetName,
		String outCharsetName) throws FileNotFoundException, IOException {
	if (filePath == null) {
		return null;
	}
	FileInputStream fis = new FileInputStream(new File(filePath));
	FileChannel fc = fis.getChannel();
	ByteBuffer byteBuffer = ByteBuffer.allocate(fis.available());
	ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

	while (true) {
		int count = fc.read(buffer);
		if (count == -1) {
			break;
		}
		buffer.flip();
		byteBuffer.put(buffer);
		buffer.clear();
	}
	fc.close();
	fis.close();
	byteBuffer.flip();
	Charset inCharset = Charset.forName(inCharsetName);
	Charset outCharset = Charset.forName(outCharsetName);
	CharsetDecoder decoder = inCharset.newDecoder();
	CharsetEncoder encoder = outCharset.newEncoder();
	CharBuffer charBuffer = decoder.decode(byteBuffer);
	ByteBuffer resultBuffer = encoder.encode(charBuffer);
	int size = resultBuffer.limit();
	byte[] data = new byte[size];
	resultBuffer.get(data, 0, size);
	return data;
}
 
Example 7
Source File: ISO2022_CN_GB.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public Encoder(Charset cs)
{
    super(cs);
    SODesig = "$)A";

    try {
        Charset cset = Charset.forName("EUC_CN"); // GB2312
        ISOEncoder = cset.newEncoder();
    } catch (Exception e) { }
}
 
Example 8
Source File: ISO2022_CN_GB.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public Encoder(Charset cs)
{
    super(cs);
    SODesig = "$)A";

    try {
        Charset cset = Charset.forName("EUC_CN"); // GB2312
        ISOEncoder = cset.newEncoder();
    } catch (Exception e) { }
}
 
Example 9
Source File: XMLWriter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public XMLWriter(OutputStream os, String encoding, Charset cs) throws XMLStreamException {
    _encoder = cs.newEncoder();
    try {
        _writer = getWriter(os, encoding, cs);
    } catch (UnsupportedEncodingException ex) {
        throw new XMLStreamException(ex);
    }

}
 
Example 10
Source File: Main.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void initializeConverter() throws UnsupportedEncodingException {
    Charset cs = null;

    try {
        cs = (encodingString == null) ?
            lookupCharset(defaultEncoding):
            lookupCharset(encodingString);

        encoder =  (cs != null) ?
            cs.newEncoder() :
            null;
    } catch (IllegalCharsetNameException e) {
        throw new Error(e);
    }
}
 
Example 11
Source File: Main.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void initializeConverter() throws UnsupportedEncodingException {
    Charset cs = null;

    try {
        cs = (encodingString == null) ?
            lookupCharset(defaultEncoding):
            lookupCharset(encodingString);

        encoder =  (cs != null) ?
            cs.newEncoder() :
            null;
    } catch (IllegalCharsetNameException e) {
        throw new Error(e);
    }
}
 
Example 12
Source File: Main.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void initializeConverter() throws UnsupportedEncodingException {
    Charset cs = null;

    try {
        cs = (encodingString == null) ?
            lookupCharset(defaultEncoding):
            lookupCharset(encodingString);

        encoder =  (cs != null) ?
            cs.newEncoder() :
            null;
    } catch (IllegalCharsetNameException e) {
        throw new Error(e);
    }
}
 
Example 13
Source File: StringCoding.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static byte[] encode(Charset cs, char[] ca, int off, int len) {
    CharsetEncoder ce = cs.newEncoder();
    int en = scale(len, ce.maxBytesPerChar());
    byte[] ba = new byte[en];
    if (len == 0)
        return ba;
    boolean isTrusted = false;
    if (System.getSecurityManager() != null) {
        if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
            ca =  Arrays.copyOfRange(ca, off, off + len);
            off = 0;
        }
    }
    ce.onMalformedInput(CodingErrorAction.REPLACE)
      .onUnmappableCharacter(CodingErrorAction.REPLACE)
      .reset();
    if (ce instanceof ArrayEncoder) {
        int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
        return safeTrim(ba, blen, cs, isTrusted);
    } else {
        ByteBuffer bb = ByteBuffer.wrap(ba);
        CharBuffer cb = CharBuffer.wrap(ca, off, len);
        try {
            CoderResult cr = ce.encode(cb, bb, true);
            if (!cr.isUnderflow())
                cr.throwException();
            cr = ce.flush(bb);
            if (!cr.isUnderflow())
                cr.throwException();
        } catch (CharacterCodingException x) {
            throw new Error(x);
        }
        return safeTrim(ba, bb.position(), cs, isTrusted);
    }
}
 
Example 14
Source File: ISO2022_CN_GB.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public Encoder(Charset cs)
{
    super(cs);
    SODesig = "$)A";

    try {
        Charset cset = Charset.forName("EUC_CN"); // GB2312
        ISOEncoder = cset.newEncoder();
    } catch (Exception e) { }
}
 
Example 15
Source File: C2BConverter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public C2BConverter(Charset charset) {
    encoder = charset.newEncoder();
    encoder.onUnmappableCharacter(CodingErrorAction.REPLACE)
            .onMalformedInput(CodingErrorAction.REPLACE);
    char[] left = new char[4];
    leftovers = CharBuffer.wrap(left);
}
 
Example 16
Source File: Files.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Write lines of text to a file. Each line is a char sequence and is
 * written to the file in sequence with each line terminated by the
 * platform's line separator, as defined by the system property {@code
 * line.separator}. Characters are encoded into bytes using the specified
 * charset.
 *
 * <p> The {@code options} parameter specifies how the the file is created
 * or opened. If no options are present then this method works as if the
 * {@link StandardOpenOption#CREATE CREATE}, {@link
 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link
 * StandardOpenOption#WRITE WRITE} options are present. In other words, it
 * opens the file for writing, creating the file if it doesn't exist, or
 * initially truncating an existing {@link #isRegularFile regular-file} to
 * a size of {@code 0}. The method ensures that the file is closed when all
 * lines have been written (or an I/O error or other runtime exception is
 * thrown). If an I/O error occurs then it may do so after the file has
 * created or truncated, or after some bytes have been written to the file.
 *
 * @param   path
 *          the path to the file
 * @param   lines
 *          an object to iterate over the char sequences
 * @param   cs
 *          the charset to use for encoding
 * @param   options
 *          options specifying how the file is opened
 *
 * @return  the path
 *
 * @throws  IOException
 *          if an I/O error occurs writing to or creating the file, or the
 *          text cannot be encoded using the specified charset
 * @throws  UnsupportedOperationException
 *          if an unsupported option is specified
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkWrite(String) checkWrite}
 *          method is invoked to check write access to the file.
 */
public static Path write(Path path, Iterable<? extends CharSequence> lines,
                         Charset cs, OpenOption... options)
    throws IOException
{
    // ensure lines is not null before opening file
    Objects.requireNonNull(lines);
    CharsetEncoder encoder = cs.newEncoder();
    OutputStream out = newOutputStream(path, options);
    try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {
        for (CharSequence line: lines) {
            writer.append(line);
            writer.newLine();
        }
    }
    return path;
}
 
Example 17
Source File: XMLEncoder.java    From jdk-1.7-annotated with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new XML encoder to write out <em>JavaBeans</em>
 * to the stream <code>out</code> using the given <code>charset</code>
 * starting from the given <code>indentation</code>.
 *
 * @param out          the stream to which the XML representation of
 *                     the objects will be written
 * @param charset      the name of the requested charset;
 *                     may be either a canonical name or an alias
 * @param declaration  whether the XML declaration should be generated;
 *                     set this to <code>false</code>
 *                     when embedding the contents in another XML document
 * @param indentation  the number of space characters to indent the entire XML document by
 *
 * @throws  IllegalArgumentException
 *          if <code>out</code> or <code>charset</code> is <code>null</code>,
 *          or if <code>indentation</code> is less than 0
 *
 * @throws  IllegalCharsetNameException
 *          if <code>charset</code> name is illegal
 *
 * @throws  UnsupportedCharsetException
 *          if no support for the named charset is available
 *          in this instance of the Java virtual machine
 *
 * @throws  UnsupportedOperationException
 *          if loaded charset does not support encoding
 *
 * @see Charset#forName(String)
 *
 * @since 1.7
 */
public XMLEncoder(OutputStream out, String charset, boolean declaration, int indentation) {
    if (out == null) {
        throw new IllegalArgumentException("the output stream cannot be null");
    }
    if (indentation < 0) {
        throw new IllegalArgumentException("the indentation must be >= 0");
    }
    Charset cs = Charset.forName(charset);
    this.encoder = cs.newEncoder();
    this.charset = charset;
    this.declaration = declaration;
    this.indentation = indentation;
    this.out = new OutputStreamWriter(out, cs.newEncoder());
    valueToExpression = new IdentityHashMap<Object, ValueData>();
    targetToStatementList = new IdentityHashMap<Object, List<Statement>>();
    nameGenerator = new NameGenerator();
}
 
Example 18
Source File: ConvertCharacterSet.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final ComponentLog logger = getLogger();

    final Charset inputCharset = Charset.forName(context.getProperty(INPUT_CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    final Charset outputCharset = Charset.forName(context.getProperty(OUTPUT_CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    final CharBuffer charBuffer = CharBuffer.allocate(MAX_BUFFER_SIZE);

    final CharsetDecoder decoder = inputCharset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    decoder.replaceWith("?");

    final CharsetEncoder encoder = outputCharset.newEncoder();
    encoder.onMalformedInput(CodingErrorAction.REPLACE);
    encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    encoder.replaceWith("?".getBytes(outputCharset));

    try {
        final StopWatch stopWatch = new StopWatch(true);
        flowFile = session.write(flowFile, new StreamCallback() {
            @Override
            public void process(final InputStream rawIn, final OutputStream rawOut) throws IOException {
                try (final BufferedReader reader = new BufferedReader(new InputStreamReader(rawIn, decoder), MAX_BUFFER_SIZE);
                        final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(rawOut, encoder), MAX_BUFFER_SIZE)) {
                    int charsRead;
                    while ((charsRead = reader.read(charBuffer)) != -1) {
                        charBuffer.flip();
                        writer.write(charBuffer.array(), 0, charsRead);
                    }

                    writer.flush();
                }
            }
        });

        session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
        logger.info("successfully converted characters from {} to {} for {}",
                new Object[]{inputCharset, outputCharset, flowFile});
        session.transfer(flowFile, REL_SUCCESS);
    } catch (final Exception e) {
        throw new ProcessException(e);
    }
}
 
Example 19
Source File: Renderer.java    From vespa with Apache License 2.0 4 votes vote down vote up
private Writer createWriter(OutputStream stream,Result result) {
    Charset cs = Charset.forName(getCharacterEncoding(result));
    CharsetEncoder encoder = cs.newEncoder();
    return new ByteWriter(stream, encoder);
}
 
Example 20
Source File: Files.java    From Java8CN with Apache License 2.0 3 votes vote down vote up
/**
 * Opens or creates a file for writing, returning a {@code BufferedWriter}
 * that may be used to write text to the file in an efficient manner.
 * The {@code options} parameter specifies how the the file is created or
 * opened. If no options are present then this method works as if the {@link
 * StandardOpenOption#CREATE CREATE}, {@link
 * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link
 * StandardOpenOption#WRITE WRITE} options are present. In other words, it
 * opens the file for writing, creating the file if it doesn't exist, or
 * initially truncating an existing {@link #isRegularFile regular-file} to
 * a size of {@code 0} if it exists.
 *
 * <p> The {@code Writer} methods to write text throw {@code IOException}
 * if the text cannot be encoded using the specified charset.
 *
 * @param   path
 *          the path to the file
 * @param   cs
 *          the charset to use for encoding
 * @param   options
 *          options specifying how the file is opened
 *
 * @return  a new buffered writer, with default buffer size, to write text
 *          to the file
 *
 * @throws  IOException
 *          if an I/O error occurs opening or creating the file
 * @throws  UnsupportedOperationException
 *          if an unsupported option is specified
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkWrite(String) checkWrite}
 *          method is invoked to check write access to the file.
 *
 * @see #write(Path,Iterable,Charset,OpenOption[])
 */
public static BufferedWriter newBufferedWriter(Path path, Charset cs,
                                               OpenOption... options)
    throws IOException
{
    CharsetEncoder encoder = cs.newEncoder();
    Writer writer = new OutputStreamWriter(newOutputStream(path, options), encoder);
    return new BufferedWriter(writer);
}