java.nio.charset.Charset#newEncoder ( )源码实例Demo

下面列出了java.nio.charset.Charset#newEncoder ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: protools   文件: ToolBarCode.java

/**
     * 生成带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);
    }
 
源代码2 项目: cups4j   文件: IppUtil.java

/**
 * 
 * @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();
}
 
源代码3 项目: tn5250j   文件: JavaCodePageFactory.java

/**
 * @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;
}
 
源代码4 项目: ion-java   文件: _Private_Utils.java

/**
 * 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);
    }
}
 

public C2BConverter(Charset charset) {
    encoder = charset.newEncoder();
    encoder.onUnmappableCharacter(CodingErrorAction.REPLACE)
            .onMalformedInput(CodingErrorAction.REPLACE);
    char[] left = new char[4];
    leftovers = CharBuffer.wrap(left);
}
 
源代码6 项目: openjdk-jdk8u   文件: ISO2022_CN_GB.java

public Encoder(Charset cs)
{
    super(cs);
    SODesig = "$)A";

    try {
        Charset cset = Charset.forName("EUC_CN"); // GB2312
        ISOEncoder = cset.newEncoder();
    } catch (Exception e) { }
}
 
源代码7 项目: openjdk-8   文件: XMLWriter.java

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);
    }

}
 
源代码8 项目: MyTv   文件: FileUtils.java

/**
 * 以指定编码读入本地文件,以指定编码方式输出,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;
}
 
源代码9 项目: jdk8u_jdk   文件: ISO2022_CN_GB.java

public Encoder(Charset cs)
{
    super(cs);
    SODesig = "$)A";

    try {
        Charset cset = Charset.forName("EUC_CN"); // GB2312
        ISOEncoder = cset.newEncoder();
    } catch (Exception e) { }
}
 
源代码10 项目: hottub   文件: XMLWriter.java

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);
    }

}
 
源代码11 项目: openjdk-jdk8u   文件: Main.java

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);
    }
}
 
源代码12 项目: TencentKona-8   文件: Main.java

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);
    }
}
 
源代码13 项目: hottub   文件: Main.java

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);
    }
}
 
源代码14 项目: jdk8u60   文件: StringCoding.java

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);
    }
}
 
源代码15 项目: jdk8u-jdk   文件: ISO2022_CN_GB.java

public Encoder(Charset cs)
{
    super(cs);
    SODesig = "$)A";

    try {
        Charset cset = Charset.forName("EUC_CN"); // GB2312
        ISOEncoder = cset.newEncoder();
    } catch (Exception e) { }
}
 
源代码16 项目: jdk8u-jdk   文件: Files.java

/**
 * 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;
}
 
源代码17 项目: jdk-1.7-annotated   文件: XMLEncoder.java

/**
 * 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();
}
 
源代码18 项目: nifi   文件: ConvertCharacterSet.java

@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);
    }
}
 
源代码19 项目: vespa   文件: Renderer.java

private Writer createWriter(OutputStream stream,Result result) {
    Charset cs = Charset.forName(getCharacterEncoding(result));
    CharsetEncoder encoder = cs.newEncoder();
    return new ByteWriter(stream, encoder);
}
 
源代码20 项目: Java8CN   文件: Files.java

/**
 * 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);
}