Java Code Examples for java.nio.charset.Charset.forName()

The following are Jave code examples for showing how to use forName() of the java.nio.charset.Charset class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: QuakeRepor   File: Query.java   View Source Code Vote up 7 votes
private static String readFromSream(InputStream inputStream) throws IOException {
    //采用StringBuilder来进行流处理
    StringBuilder output = new StringBuilder();
    if (inputStream !=null){
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line = reader.readLine();
        while (line !=null){
            output.append(line);
            line  =reader.readLine();
        }
    }

    return output.toString();

}
 
Example 2
Project: FApkSigner   File: PasswordRetriever.java   View Source Code Vote up 6 votes
public static Charset getCharsetByName(String charsetName) throws IllegalArgumentException {
    // On Windows 10, cp65001 is the UTF-8 code page. For some reason, popular JVMs don't
    // have a mapping for cp65001...
    if ("cp65001".equalsIgnoreCase(charsetName)) {
        return StandardCharsets.UTF_8;
    }
    return Charset.forName(charsetName);
}
 
Example 3
Project: OpenJSharp   File: IPPPrintService.java   View Source Code Vote up 6 votes
public synchronized boolean isPostscript() {
    if (isPS == null) {
       isPS = Boolean.TRUE;
        if (isCupsPrinter) {
            try {
                urlConnection = getIPPConnection(
                                         new URL(myURL+".ppd"));

               InputStream is = urlConnection.getInputStream();
               if (is != null) {
                   BufferedReader d =
                       new BufferedReader(new InputStreamReader(is,
                                                      Charset.forName("ISO-8859-1")));
                   String lineStr;
                   while ((lineStr = d.readLine()) != null) {
                       if (lineStr.startsWith("*cupsFilter:")) {
                           isPS = Boolean.FALSE;
                           break;
                       }
                   }
                }
            } catch (java.io.IOException e) {
                debug_println(" isPostscript, e= "+e);
                /* if PPD is not found, this may be a raw printer
                   and in this case it is assumed that it is a
                   Postscript printer */
                // do nothing
            }
        }
    }
    return isPS.booleanValue();
}
 
Example 4
Project: openjdk-jdk10   File: CodeSetConversion.java   View Source Code Vote up 6 votes
public JavaCTBConverter(OSFCodeSetRegistry.Entry codeset,
                        int alignmentForEncoding) {

    try {
        ctb = cache.getCharToByteConverter(codeset.getName());
        if (ctb == null) {
            Charset tmpCharset = Charset.forName(codeset.getName());
            ctb = tmpCharset.newEncoder();
            cache.setConverter(codeset.getName(), ctb);
        }
    } catch(IllegalCharsetNameException icne) {

        // This can only happen if one of our Entries has
        // an invalid name.
        throw wrapper.invalidCtbConverterName(icne,codeset.getName());
    } catch(UnsupportedCharsetException ucne) {

        // This can only happen if one of our Entries has
        // an unsupported name.
        throw wrapper.invalidCtbConverterName(ucne,codeset.getName());
    }

    this.codeset = codeset;
    alignment = alignmentForEncoding;
}
 
Example 5
Project: uckefu   File: UKResultMapper.java   View Source Code Vote up 6 votes
private String buildJSONFromFields(Collection<SearchHitField> values) {
	JsonFactory nodeFactory = new JsonFactory();
	try {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
		generator.writeStartObject();
		for (SearchHitField value : values) {
			if (value.getValues().size() > 1) {
				generator.writeArrayFieldStart(value.getName());
				for (Object val : value.getValues()) {
					generator.writeObject(val);
				}
				generator.writeEndArray();
			} else {
				generator.writeObjectField(value.getName(), value.getValue());
			}
		}
		generator.writeEndObject();
		generator.flush();
		return new String(stream.toByteArray(), Charset.forName("UTF-8"));
	} catch (IOException e) {
		return null;
	}
}
 
Example 6
Project: incubator-netbeans   File: BufferedCharSequenceTest.java   View Source Code Vote up 6 votes
@Test
 public void testCharAt$10_byte() {
     System.out.println("testCharAt$10_byte");
     File file = getFile("10_bytes");
     Charset cs = Charset.forName(UTF_8);
     for(TypeOfStream stype: TypeOfStream.values()) {
         InputStream stream = getInputStream(stype, TypeOfContent.BYTE_10, cs);
         BufferedCharSequence instance = new BufferedCharSequence(stream, cs.newDecoder(), 10);
         instance.setMaxBufferSize(10);
         char result;

         result = instance.charAt(0);
         assertEquals('0', result);

         result = instance.charAt(9);
         assertEquals('9', result);

         result = instance.charAt(5);
         assertEquals('5', result);

         result = instance.charAt(9);
         assertEquals('9', result);
     }
}
 
Example 7
Project: hadoop   File: ClusterCLI.java   View Source Code Vote up 5 votes
@VisibleForTesting
void printUsage(Options opts) throws UnsupportedEncodingException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PrintWriter pw =
      new PrintWriter(new OutputStreamWriter(baos, Charset.forName("UTF-8")));
  new HelpFormatter().printHelp(pw, HelpFormatter.DEFAULT_WIDTH, TITLE, null,
      opts, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD,
      null);
  pw.close();
  sysout.println(baos.toString("UTF-8"));
}
 
Example 8
Project: jdk8u-jdk   File: XMLFormatter.java   View Source Code Vote up 5 votes
/**
 * Return the header string for a set of XML formatted records.
 *
 * @param   h  The target handler (can be null)
 * @return  a valid XML string
 */
public String getHead(Handler h) {
    StringBuilder sb = new StringBuilder();
    String encoding;
    sb.append("<?xml version=\"1.0\"");

    if (h != null) {
        encoding = h.getEncoding();
    } else {
        encoding = null;
    }

    if (encoding == null) {
        // Figure out the default encoding.
        encoding = java.nio.charset.Charset.defaultCharset().name();
    }
    // Try to map the encoding name to a canonical name.
    try {
        Charset cs = Charset.forName(encoding);
        encoding = cs.name();
    } catch (Exception ex) {
        // We hit problems finding a canonical name.
        // Just use the raw encoding name.
    }

    sb.append(" encoding=\"");
    sb.append(encoding);
    sb.append("\"");
    sb.append(" standalone=\"no\"?>\n");
    sb.append("<!DOCTYPE log SYSTEM \"logger.dtd\">\n");
    sb.append("<log>\n");
    return sb.toString();
}
 
Example 9
Project: andcouchbaseentity   File: CodeGenerator.java   View Source Code Vote up 5 votes
private Charset getCharset() {
    try {
        return Charset.forName(encoding);
    } catch (UnsupportedCharsetException exception) {
        Charset defaultCharset = Charset.defaultCharset();
        return defaultCharset;
    }
}
 
Example 10
Project: OpenDiabetes   File: AllTests.java   View Source Code Vote up 5 votes
@Test
public void test112() throws Exception {
	try {
		new CsvWriter((String) null, ',', Charset
				.forName("ISO-8859-1"));
	} catch (Exception ex) {
		assertException(new IllegalArgumentException("Parameter fileName can not be null."), ex);
	}
}
 
Example 11
Project: edoras-one-initializr   File: TemplateRenderer.java   View Source Code Vote up 5 votes
private static TemplateLoader mustacheTemplateLoader() {
	ResourceLoader resourceLoader = new DefaultResourceLoader();
	String prefix = "classpath:/templates/";
	Charset charset = Charset.forName("UTF-8");
	return name -> new InputStreamReader(
			resourceLoader.getResource(prefix + name).getInputStream(), charset);
}
 
Example 12
Project: storm-dynamic-spout   File: ZookeeperWatchTrigger.java   View Source Code Vote up 4 votes
/**
 * Create a trigger event from the provided data.
 * @return Trigger event
 */
private TriggerEvent getTriggerEvent(final byte[] data) {
    final String json = new String(data, Charset.forName("UTF-8"));
    return getTriggerEventFromJson(json);
}
 
Example 13
Project: spring-cloud-skipper   File: DeleteDocumentation.java   View Source Code Vote up 4 votes
@Test
public void deleteReleaseDefault() throws Exception {
	final String releaseName = "myLogRelease1";
	final InstallRequest installRequest = new InstallRequest();
	final PackageIdentifier packageIdentifier = new PackageIdentifier();
	packageIdentifier.setPackageName("log");
	packageIdentifier.setPackageVersion("1.0.0");
	packageIdentifier.setRepositoryName("notused");
	installRequest.setPackageIdentifier(packageIdentifier);
	installRequest.setInstallProperties(createInstallProperties(releaseName));

	installPackage(installRequest);

	final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
			MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

	this.mockMvc.perform(
			delete("/api/release/{releaseName}", releaseName)
					.accept(MediaType.APPLICATION_JSON).contentType(contentType))
			.andDo(print())
			.andExpect(status().isOk())
			.andDo(this.documentationHandler.document(
					responseFields(
							subsectionWithPath("links").ignored(),
							fieldWithPath("name").description("Name of the release"),
							fieldWithPath("version").description("Version of the release"),
							fieldWithPath("info.status.statusCode").description(
									String.format("StatusCode of the release's status (%s)",
											StringUtils.arrayToCommaDelimitedString(StatusCode.values()))),
							fieldWithPath("info.status.platformStatus")
									.description("Status from the underlying platform"),
							fieldWithPath("info.firstDeployed").description("Date/Time of first deployment"),
							fieldWithPath("info.lastDeployed").description("Date/Time of last deployment"),
							fieldWithPath("info.deleted").description("Date/Time of when the release was deleted"),
							fieldWithPath("info.description")
									.description("Human-friendly 'log entry' about this release"),
							fieldWithPath("pkg.metadata.apiVersion")
									.description("The Package Index spec version this file is based on"),
							fieldWithPath("pkg.metadata.origin")
									.description("Indicates the origin of the repository (free form text)"),
							fieldWithPath("pkg.metadata.repositoryId")
									.description("The repository ID this Package belongs to."),
							fieldWithPath("pkg.metadata.repositoryName")
									.description("The repository name this Package belongs to."),
							fieldWithPath("pkg.metadata.kind")
									.description("What type of package system is being used"),
							fieldWithPath("pkg.metadata.name").description("The name of the package"),
							fieldWithPath("pkg.metadata.displayName").description("Display name of the release"),
							fieldWithPath("pkg.metadata.version").description("The version of the package"),
							fieldWithPath("pkg.metadata.packageSourceUrl")
									.description("Location to source code for this package"),
							fieldWithPath("pkg.metadata.packageHomeUrl")
									.description("The home page of the package"),
							fieldWithPath("pkg.metadata.tags")
									.description("A comma separated list of tags to use for searching"),
							fieldWithPath("pkg.metadata.maintainer").description("Who is maintaining this package"),
							fieldWithPath("pkg.metadata.description")
									.description("Brief description of the package"),
							fieldWithPath("pkg.metadata.sha256").description(
									"Hash of package binary that will be downloaded using SHA256 hash algorithm"),
							fieldWithPath("pkg.metadata.iconUrl").description("Url location of a icon"),
							fieldWithPath("pkg.templates[].name")
									.description("Name is the path-like name of the template"),
							fieldWithPath("pkg.templates[].data")
									.description("Data is the template as string data"),
							fieldWithPath("pkg.dependencies")
									.description("The packages that this package depends upon"),
							fieldWithPath("pkg.configValues.raw")
									.description("The raw YAML string of configuration values"),
							fieldWithPath("pkg.fileHolders")
									.description("Miscellaneous files in a package, e.g. README, LICENSE, etc."),
							fieldWithPath("configValues.raw")
									.description("The raw YAML string of configuration values"),
							fieldWithPath("manifest.data").description("The manifest of the release"),
							fieldWithPath("platformName").description("Platform name of the release"))));
}
 
Example 14
Project: openjdk-jdk10   File: ToolBox.java   View Source Code Vote up 4 votes
private Charset getCharset(String encoding) {
    return (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding);
}
 
Example 15
Project: nymph   File: HttpChannel.java   View Source Code Vote up 4 votes
public void setCharset(String charset) {
    this.charset = Charset.forName(charset);
}
 
Example 16
Project: cordova-logcat-filelogger   File: ReversedLinesFileReader.java   View Source Code Vote up 4 votes
/**
 * Creates a ReversedLinesFileReader with the given block size and encoding.
 *
 * @param file
 *            the file to be read
 * @param blockSize
 *            size of the internal buffer (for ideal performance this should
 *            match with the block size of the underlying file system).
 * @param encoding
 *            the encoding of the file
 * @throws IOException  if an I/O error occurs
 * @since 2.3
 */
@SuppressWarnings("deprecation") // unavoidable until Java 7
public ReversedLinesFileReader(final File file, final int blockSize, final Charset encoding) throws IOException {
    this.blockSize = blockSize;
    this.encoding = encoding;

    // --- check & prepare encoding ---
    final Charset charset = Charsets.toCharset(encoding);
    final CharsetEncoder charsetEncoder = charset.newEncoder();
    final float maxBytesPerChar = charsetEncoder.maxBytesPerChar();
    if (maxBytesPerChar == 1f) {
        // all one byte encodings are no problem
        byteDecrement = 1;
    } else if (charset == Charsets.UTF_8) {
        // UTF-8 works fine out of the box, for multibyte sequences a second UTF-8 byte can never be a newline byte
        // http://en.wikipedia.org/wiki/UTF-8
        byteDecrement = 1;
    } else if(charset == Charset.forName("Shift_JIS") || // Same as for UTF-8
            // http://www.herongyang.com/Unicode/JIS-Shift-JIS-Encoding.html
            charset == Charset.forName("windows-31j") || // Windows code page 932 (Japanese)
            charset == Charset.forName("x-windows-949") || // Windows code page 949 (Korean)
            charset == Charset.forName("gbk") || // Windows code page 936 (Simplified Chinese)
            charset == Charset.forName("x-windows-950")) { // Windows code page 950 (Traditional Chinese)
        byteDecrement = 1;
    } else if (charset == Charsets.UTF_16BE || charset == Charsets.UTF_16LE) {
        // UTF-16 new line sequences are not allowed as second tuple of four byte sequences,
        // however byte order has to be specified
        byteDecrement = 2;
    } else if (charset == Charsets.UTF_16) {
        throw new UnsupportedEncodingException("For UTF-16, you need to specify the byte order (use UTF-16BE or " +
                "UTF-16LE)");
    } else {
        throw new UnsupportedEncodingException("Encoding " + encoding + " is not supported yet (feel free to " +
                "submit a patch)");
    }

    // NOTE: The new line sequences are matched in the order given, so it is important that \r\n is BEFORE \n
    newLineSequences = new byte[][] { "\r\n".getBytes(encoding), "\n".getBytes(encoding), "\r".getBytes(encoding) };

    avoidNewlineSplitBufferSize = newLineSequences[0].length;

    // Open file
    randomAccessFile = new RandomAccessFile(file, "r");
    totalByteLength = randomAccessFile.length();
    int lastBlockLength = (int) (totalByteLength % blockSize);
    if (lastBlockLength > 0) {
        totalBlockCount = totalByteLength / blockSize + 1;
    } else {
        totalBlockCount = totalByteLength / blockSize;
        if (totalByteLength > 0) {
            lastBlockLength = blockSize;
        }
    }
    currentFilePart = new FilePart(totalBlockCount, lastBlockLength, null);

}
 
Example 17
Project: lams   File: ReversedLinesFileReader.java   View Source Code Vote up 4 votes
/**
 * Creates a ReversedLinesFileReader with the given block size and encoding.
 *
 * @param file
 *            the file to be read
 * @param blockSize
 *            size of the internal buffer (for ideal performance this should
 *            match with the block size of the underlying file system).
 * @param encoding
 *            the encoding of the file
 * @throws IOException  if an I/O error occurs
 * @since 2.3
 */
public ReversedLinesFileReader(final File file, final int blockSize, final Charset encoding) throws IOException {
    this.blockSize = blockSize;
    this.encoding = encoding;

    randomAccessFile = new RandomAccessFile(file, "r");
    totalByteLength = randomAccessFile.length();
    int lastBlockLength = (int) (totalByteLength % blockSize);
    if (lastBlockLength > 0) {
        totalBlockCount = totalByteLength / blockSize + 1;
    } else {
        totalBlockCount = totalByteLength / blockSize;
        if (totalByteLength > 0) {
            lastBlockLength = blockSize;
        }
    }
    currentFilePart = new FilePart(totalBlockCount, lastBlockLength, null);

    // --- check & prepare encoding ---
    Charset charset = Charsets.toCharset(encoding);
    CharsetEncoder charsetEncoder = charset.newEncoder();
    float maxBytesPerChar = charsetEncoder.maxBytesPerChar();
    if(maxBytesPerChar==1f) {
        // all one byte encodings are no problem
        byteDecrement = 1;
    } else if(charset == Charset.forName("UTF-8")) {
        // UTF-8 works fine out of the box, for multibyte sequences a second UTF-8 byte can never be a newline byte
        // http://en.wikipedia.org/wiki/UTF-8
        byteDecrement = 1;
    } else if(charset == Charset.forName("Shift_JIS")) {
        // Same as for UTF-8
        // http://www.herongyang.com/Unicode/JIS-Shift-JIS-Encoding.html
        byteDecrement = 1;
    } else if(charset == Charset.forName("UTF-16BE") || charset == Charset.forName("UTF-16LE")) {
        // UTF-16 new line sequences are not allowed as second tuple of four byte sequences,
        // however byte order has to be specified
        byteDecrement = 2;
    } else if(charset == Charset.forName("UTF-16")) {
        throw new UnsupportedEncodingException(
                "For UTF-16, you need to specify the byte order (use UTF-16BE or UTF-16LE)");
    } else {
        throw new UnsupportedEncodingException(
                "Encoding "+encoding+" is not supported yet (feel free to submit a patch)");
    }
    // NOTE: The new line sequences are matched in the order given, so it is important that \r\n is BEFORE \n
    newLineSequences = new byte[][] { "\r\n".getBytes(encoding), "\n".getBytes(encoding), "\r".getBytes(encoding) };

    avoidNewlineSplitBufferSize = newLineSequences[0].length;
}
 
Example 18
Project: alfresco-data-model   File: ContentCharsetFinder.java   View Source Code Vote up 2 votes
/**
 * Override the system default charset.  Where the characterset cannot be determined for
 * a mimetype and input stream, this mimetype will be used.  The default is 'UTF-8'.
 * 
 * @param defaultCharset            the default characterset
 */
public void setDefaultCharset(String defaultCharset)
{
    this.defaultCharset = Charset.forName(defaultCharset);
}
 
Example 19
Project: aos-FileCoreLibrary   File: Charsets.java   View Source Code Vote up 2 votes
/**
 * Returns a charset object for the given charset name.
 *
 * @param charsetName
 *            The name of the requested charset; may be a canonical name, an alias, or null.
 *            If null, return the default charset.
 * @param defaultCharsetName the charset name to use if the requested charset is null
 *
 * @return A charset object for the named charset
 */
public static Charset toCharset(String charsetName, String defaultCharsetName) {
    return charsetName == null ? Charset.forName(defaultCharsetName) : Charset.forName(charsetName);
}
 
Example 20
Project: WeiXinGroupSend   File: Utf7ImeHelper.java   View Source Code Vote up 2 votes
/**
 * Encodes the specified text into modified UTF-7.
 * 
 * @param text
 *            plain unicode text
 * @return encoded text in modified UTF-7.
 */
public static String e(String text) {
    byte[] encoded = getBytes(text, CHARSET_MODIFIED_UTF7);
    return new String(encoded, Charset.forName("US-ASCII"));
}