Search in sources :

Example 26 with CharsetEncoder

use of java.nio.charset.CharsetEncoder in project checker-framework by typetools.

the class StringCoding method encode.

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);
    }
}
Also used : CharBuffer(java.nio.CharBuffer) CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) ArrayEncoder(sun.nio.cs.ArrayEncoder) CoderResult(java.nio.charset.CoderResult)

Example 27 with CharsetEncoder

use of java.nio.charset.CharsetEncoder in project erlide_eclipse by erlang.

the class Util method encode.

public static byte[] encode(final String string, final String encoding) {
    final Charset charset = Charset.forName(encoding);
    final CharsetEncoder encoder = charset.newEncoder();
    try {
        final CharBuffer cbuf = CharBuffer.wrap(string);
        final ByteBuffer bbuf = encoder.encode(cbuf);
        return bbuf.array();
    } catch (final CharacterCodingException e) {
        return null;
    }
}
Also used : CharBuffer(java.nio.CharBuffer) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer)

Example 28 with CharsetEncoder

use of java.nio.charset.CharsetEncoder in project mkgmap by openstreetmap.

the class TYPFile method writeLabels.

private void writeLabels(ImgFileWriter in) {
    if (data.getIcons().isEmpty())
        return;
    SectionWriter writer = header.getLabels().makeSectionWriter(in);
    List<SortKey<TypIconSet>> keys = new ArrayList<SortKey<TypIconSet>>();
    Sort sort = data.getSort();
    for (TypIconSet icon : data.getIcons()) {
        String label = icon.getLabel();
        if (label != null) {
            SortKey<TypIconSet> key = sort.createSortKey(icon, label);
            keys.add(key);
        }
    }
    Collections.sort(keys);
    // Offset 0 is reserved to mean no label.
    writer.put((byte) 0);
    for (SortKey<TypIconSet> key : keys) {
        int off = writer.position();
        TypIconSet icon = key.getObject();
        int type = icon.getTypeForFile();
        String label = icon.getLabel();
        if (label != null) {
            CharBuffer cb = CharBuffer.wrap(label);
            CharsetEncoder encoder = data.getEncoder();
            try {
                ByteBuffer buffer = encoder.encode(cb);
                writer.put(buffer);
                // If we succeeded then note offsets for indexes
                strToType.put(off, type);
                typeToStr.put(type, off);
            } catch (CharacterCodingException ignore) {
                String name = encoder.charset().name();
                throw new TypLabelException(name);
            }
            writer.put((byte) 0);
        }
    }
    Utils.closeFile(writer);
}
Also used : SectionWriter(uk.me.parabola.imgfmt.app.SectionWriter) ArrayList(java.util.ArrayList) CharBuffer(java.nio.CharBuffer) SortKey(uk.me.parabola.imgfmt.app.srt.SortKey) CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) Sort(uk.me.parabola.imgfmt.app.srt.Sort)

Example 29 with CharsetEncoder

use of java.nio.charset.CharsetEncoder in project mkgmap by openstreetmap.

the class TYPFile method writeSection.

private void writeSection(ImgFileWriter writer, Section dataSection, Section indexSection, List<? extends TypElement> elementData) {
    Collections.sort(elementData);
    SectionWriter subWriter = dataSection.makeSectionWriter(writer);
    CharsetEncoder encoder = data.getEncoder();
    for (TypElement elem : elementData) elem.write(subWriter, encoder);
    Utils.closeFile(subWriter);
    int size = dataSection.getSize();
    int typeSize = indexSection.getItemSize();
    int psize = Utils.numberToPointerSize(size);
    indexSection.setItemSize((char) (typeSize + psize));
    subWriter = indexSection.makeSectionWriter(writer);
    for (TypElement elem : elementData) {
        int offset = elem.getOffset();
        int type = elem.getTypeForFile();
        subWriter.putN(typeSize, type);
        subWriter.putN(psize, offset);
    }
    Utils.closeFile(subWriter);
    zapZero(dataSection, indexSection);
}
Also used : SectionWriter(uk.me.parabola.imgfmt.app.SectionWriter) CharsetEncoder(java.nio.charset.CharsetEncoder)

Example 30 with CharsetEncoder

use of java.nio.charset.CharsetEncoder in project Bytecoder by mirkosertic.

the class Files method write.

/**
 * 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 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
 * been 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  IllegalArgumentException
 *          if {@code options} contains an invalid combination of options
 * @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. The {@link
 *          SecurityManager#checkDelete(String) checkDelete} method is
 *          invoked to check delete access if the file is opened with the
 *          {@code DELETE_ON_CLOSE} option.
 */
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;
}
Also used : OutputStream(java.io.OutputStream) OutputStreamWriter(java.io.OutputStreamWriter) CharsetEncoder(java.nio.charset.CharsetEncoder) BufferedWriter(java.io.BufferedWriter)

Aggregations

CharsetEncoder (java.nio.charset.CharsetEncoder)177 ByteBuffer (java.nio.ByteBuffer)87 Charset (java.nio.charset.Charset)50 CharBuffer (java.nio.CharBuffer)42 CharacterCodingException (java.nio.charset.CharacterCodingException)31 CoderResult (java.nio.charset.CoderResult)31 OutputStreamWriter (java.io.OutputStreamWriter)21 IOException (java.io.IOException)15 BufferedWriter (java.io.BufferedWriter)13 OutputStream (java.io.OutputStream)10 FileOutputStream (java.io.FileOutputStream)7 InputStream (java.io.InputStream)7 IStatus (org.eclipse.core.runtime.IStatus)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)6 CoreException (org.eclipse.core.runtime.CoreException)6 Status (org.eclipse.core.runtime.Status)6 ArrayEncoder (sun.nio.cs.ArrayEncoder)6 Writer (java.io.Writer)5