本文整理汇总了Java中java.nio.charset.Charset类的典型用法代码示例。如果您正苦于以下问题:Java Charset类的具体用法?Java Charset怎么用?Java Charset使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Charset类属于java.nio.charset包,在下文中一共展示了Charset类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeRequest
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Sends a POST request to the service at {@code serviceUrl} with a payload of {@code request}.
* The request type is determined by the {@code headers} param.
*
* @param request A {@link String} representation of a request object. Can be JSON object, form data, etc...
* @param serviceUrl The service URL to sent the request to
* @param headers An array of {@link Header} objects, used to determine the request type
* @return {@link String} response from the service (representing JSON object)
* @throws IOException if the connection is interrupted or the response is unparsable
*/
public String executeRequest(String request, String serviceUrl, Header[] headers) throws IOException {
HttpPost httpPost = new HttpPost(serviceUrl);
httpPost.setHeaders(headers);
httpPost.setEntity(new StringEntity(request, Charset.forName("UTF-8")));
if (logger.isDebugEnabled()) {
logger.debug("Sent " + request);
}
HttpResponse response = httpClient.execute(httpPost);
String responseJSON = EntityUtils.toString(response.getEntity(), UTF8_CHARSET);
if (logger.isDebugEnabled()) {
logger.debug("Received " + responseJSON);
}
return responseJSON;
}
示例2: writeLines
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Writes the <code>toString()</code> value of each item in a collection to
* an <code>OutputStream</code> line by line, using the specified character
* encoding and the specified line ending.
*
* @param lines the lines to write, null entries produce blank lines
* @param lineEnding the line separator to use, null is system default
* @param output the <code>OutputStream</code> to write to, not null, not closed
* @param encoding the encoding to use, null means platform default
* @throws NullPointerException if the output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void writeLines(Collection<?> lines, String lineEnding, OutputStream output, Charset encoding)
throws IOException {
if (lines == null) {
return;
}
if (lineEnding == null) {
lineEnding = LINE_SEPARATOR;
}
Charset cs = Charsets.toCharset(encoding);
for (Object line : lines) {
if (line != null) {
output.write(line.toString().getBytes(cs));
}
output.write(lineEnding.getBytes(cs));
}
}
示例3: generate
import java.nio.charset.Charset; //导入依赖的package包/类
@Override
public String generate(final Principal principal, final Service service) {
try {
final MessageDigest md = MessageDigest.getInstance("SHA");
final Charset charset = Charset.defaultCharset();
md.update(service.getId().getBytes(charset));
md.update(CONST_SEPARATOR);
md.update(principal.getId().getBytes(charset));
md.update(CONST_SEPARATOR);
final String result = CompressionUtils.encodeBase64(md.digest(convertSaltToByteArray()));
return result.replaceAll(System.getProperty("line.separator"), "");
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:17,代码来源:ShibbolethCompatiblePersistentIdGenerator.java
示例4: testMessageRepeat
import java.nio.charset.Charset; //导入依赖的package包/类
public void testMessageRepeat() throws Exception {
clearWorkDir();
System.setProperty("netbeans.user", getWorkDirPath());
File logs = new File(getWorkDir(), "logs");
logs.mkdirs();
MessagesHandler mh = new MessagesHandler(logs, 2, 10000);
mh.publish(new LogRecord(Level.INFO, "Hi"));
mh.publish(new LogRecord(Level.INFO, "Hello"));
mh.publish(new LogRecord(Level.INFO, "Hello"));
mh.flush();
File log = logs.listFiles()[0];
List<String> allLines = Files.readAllLines(log.toPath(), Charset.defaultCharset());
assertTrue(allLines.get(allLines.size() - 1), allLines.get(allLines.size() - 1).endsWith(MessagesHandler.getRepeatingMessage(1, 1)));
assertTrue(allLines.get(allLines.size() - 2), allLines.get(allLines.size() - 2).endsWith("Hello"));
assertTrue(allLines.get(allLines.size() - 3), allLines.get(allLines.size() - 3).endsWith("Hi"));
mh.publish(new LogRecord(Level.INFO, "Hello"));
mh.publish(new LogRecord(Level.INFO, "Hello"));
mh.flush();
allLines = Files.readAllLines(log.toPath(), Charset.defaultCharset());
assertTrue(allLines.get(allLines.size() - 1), allLines.get(allLines.size() - 1).endsWith(MessagesHandler.getRepeatingMessage(2, 2)));
}
示例5: listContainers
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Lists the containers matching the given application attempts
*
* @param appAttemptId
* @throws YarnException
* @throws IOException
*/
private void listContainers(String appAttemptId) throws YarnException,
IOException {
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(sysout, Charset.forName("UTF-8")));
List<ContainerReport> appsReport = client
.getContainers(ConverterUtils.toApplicationAttemptId(appAttemptId));
writer.println("Total number of containers " + ":" + appsReport.size());
writer.printf(CONTAINER_PATTERN, "Container-Id", "Start Time",
"Finish Time", "State", "Host", "Node Http Address", "LOG-URL");
for (ContainerReport containerReport : appsReport) {
writer.printf(
CONTAINER_PATTERN,
containerReport.getContainerId(),
Times.format(containerReport.getCreationTime()),
Times.format(containerReport.getFinishTime()),
containerReport.getContainerState(), containerReport
.getAssignedNode(), containerReport.getNodeHttpAddress() == null
? "N/A" : containerReport.getNodeHttpAddress(),
containerReport.getLogUrl());
}
writer.flush();
}
示例6: decrypt
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Decrypt the value.
*
* @param value the value
* @param hashedKey the hashed key
* @return the string
*/
protected String decrypt(final String value, final String hashedKey) {
if (value == null) {
return null;
}
try {
final Cipher cipher = getCipherObject();
final byte[] ivCiphertext = CompressionUtils.decodeBase64ToByteArray(value);
final int ivSize = byte2int(Arrays.copyOfRange(ivCiphertext, 0, INTEGER_LEN));
final byte[] ivValue = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN, (INTEGER_LEN + ivSize));
final byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN + ivSize, ivCiphertext.length);
final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
cipher.init(Cipher.DECRYPT_MODE, this.key, ivSpec);
final byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, Charset.defaultCharset());
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
示例7: getCharset
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Examine the response headers to figure out the charset used to
* encode the body content.
* If the content type is not textual, returns an empty Optional.
* Otherwise, returns the body content's charset, defaulting to
* ISO-8859-1 if none is explicitly specified.
* @param headers The response headers.
* @return The charset to use for decoding the response body, if
* the response body content is text/...
*/
public static Optional<Charset> getCharset(HttpHeaders headers) {
Optional<String> contentType = headers.firstValue("Content-Type");
Optional<Charset> charset = Optional.empty();
if (contentType.isPresent()) {
final String[] values = contentType.get().split(";");
if (values[0].startsWith("text/")) {
charset = Optional.of(Stream.of(values)
.map(x -> x.toLowerCase(Locale.ROOT))
.map(String::trim)
.filter(x -> x.startsWith("charset="))
.map(x -> x.substring("charset=".length()))
.findFirst()
.orElse("ISO-8859-1"))
.map(Charset::forName);
}
}
return charset;
}
示例8: getMemInfo
import java.nio.charset.Charset; //导入依赖的package包/类
public static Map<String,String> getMemInfo() throws IOException {
Map<String,String> rtn = new HashMap<>();
Path meminfoPath = Paths.get("/proc/meminfo");
if (Files.exists(meminfoPath)) {
List<String> lines = Files.readAllLines(meminfoPath, Charset.defaultCharset());
for(String line :lines){
String[] parts = line.split(":");
if(parts.length>1) {
rtn.put(parts[0], parts[1].trim());
}
}
}
return rtn;
}
示例9: toString
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Get the entity content as a String, using the provided default character set
* if none is found in the entity.
* If defaultCharset is null, the default "ISO-8859-1" is used.
*
* @param entity must not be null
* @param defaultCharset character set to be applied if none found in the entity,
* or if the entity provided charset is invalid or not available.
* @return the entity content as a String. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
* @throws java.nio.charset.UnsupportedCharsetException Thrown when the named entity's charset is not available in
* this instance of the Java virtual machine and no defaultCharset is provided.
*/
public static String toString(
final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
Args.notNull(entity, "Entity");
ru.radiomayak.http.entity.ContentType contentType = null;
try {
contentType = ru.radiomayak.http.entity.ContentType.get(entity);
} catch (final UnsupportedCharsetException ex) {
if (defaultCharset == null) {
throw new UnsupportedEncodingException(ex.getMessage());
}
}
if (contentType != null) {
if (contentType.getCharset() == null) {
contentType = contentType.withCharset(defaultCharset);
}
} else {
contentType = ru.radiomayak.http.entity.ContentType.DEFAULT_TEXT.withCharset(defaultCharset);
}
return toString(entity, contentType);
}
示例10: test5
import java.nio.charset.Charset; //导入依赖的package包/类
@Test(expected = Exception.class)// failure on MDC
public void test5() {
byte[] id = HashUtil.sha3("+++".getBytes(Charset.forName("UTF-8")));
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
Message findNode = FindNodeMessage.create(id, key);
logger.info("{}", findNode);
byte[] wire = findNode.getPacket();
wire[64]++;
FindNodeMessage findNode2 = (FindNodeMessage) Message.decode(wire);
logger.info("{}", findNode2);
assertEquals(findNode.toString(), findNode2.toString());
}
示例11: byteToCharArray
import java.nio.charset.Charset; //导入依赖的package包/类
private static char[] byteToCharArray(final byte[] bytes) {
Charset cs = StandardCharsets.UTF_8;
int start = 0;
// BOM detection.
if (bytes.length > 1 && bytes[0] == (byte) 0xFE && bytes[1] == (byte) 0xFF) {
start = 2;
cs = StandardCharsets.UTF_16BE;
} else if (bytes.length > 1 && bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xFE) {
start = 2;
cs = StandardCharsets.UTF_16LE;
} else if (bytes.length > 2 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
start = 3;
cs = StandardCharsets.UTF_8;
} else if (bytes.length > 3 && bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xFE && bytes[2] == 0 && bytes[3] == 0) {
start = 4;
cs = Charset.forName("UTF-32LE");
} else if (bytes.length > 3 && bytes[0] == 0 && bytes[1] == 0 && bytes[2] == (byte) 0xFE && bytes[3] == (byte) 0xFF) {
start = 4;
cs = Charset.forName("UTF-32BE");
}
return new String(bytes, start, bytes.length - start, cs).toCharArray();
}
示例12: testFilledMultiLineWithUserFieldsAndContextMapAsRootEvent
import java.nio.charset.Charset; //导入依赖的package包/类
/**
* Test filled multi line event.
*/
@Test
public void testFilledMultiLineWithUserFieldsAndContextMapAsRootEvent(){
UserField[] fields = new UserField[2];
fields[0] = new UserField("A1","B1");
fields[1] = new UserField("A2","B2");
JSONLog4j2Layout layout = new JSONLog4j2Layout(false,false,false,true,fields,Charset.forName("UTF-8"));
DummyFilledLogEvent event = new DummyFilledLogEvent(LONG_STRING);
event.getContextMap().put("CT1", "VALUE");
event.getContextMap().put("CT2", "VALUE");
System.out.println(layout.toSerializable(event));
}
示例13: getBytes
import java.nio.charset.Charset; //导入依赖的package包/类
private static void getBytes() {
System.out.println("getChars.(int srcBegin, int srcEnd, char dst[], "
+ " int dstBegin");
tryCatch(" 1, 2, null, 1", NullPointerException.class, new Runnable() {
public void run() {
"foo".getBytes(1, 2, null, 1);
}});
System.out.println("getBytes.(String charsetName)"
+ " throws UnsupportedEncodingException");
tryCatch(" null", NullPointerException.class, new Runnable() {
public void run() {
try {
"foo".getBytes((String)null);
} catch (UnsupportedEncodingException x) {
throw new RuntimeException(x);
}
}});
System.out.println("getBytes.(Charset charset)");
tryCatch(" null", NullPointerException.class, new Runnable() {
public void run() {
"foo".getBytes((Charset)null);
}});
}
示例14: createExampleSet
import java.nio.charset.Charset; //导入依赖的package包/类
public static ExampleSet createExampleSet(File file, boolean firstRowAsColumnNames, double sampleRatio, int maxLines,
String separatorRegExpr, char[] comments, int dataRowType, boolean useQuotes, boolean trimLines,
boolean skipErrorLines, char decimalPointCharacter, Charset encoding, String labelName, int labelColumn,
String idName, int idColumn, String weightName, int weightColumn) throws IOException, UserError,
IndexOutOfBoundsException {
// create attribute data sources and guess value types (performs a data scan)
AttributeDataSourceCreator adsCreator = new AttributeDataSourceCreator();
adsCreator.loadData(file, comments, separatorRegExpr, decimalPointCharacter, useQuotes, '"', '\\', trimLines,
firstRowAsColumnNames, -1, skipErrorLines, encoding, null);
List<AttributeDataSource> attributeDataSources = adsCreator.getAttributeDataSources();
// set special attributes
resetAttributeType(attributeDataSources, labelName, labelColumn, Attributes.LABEL_NAME);
resetAttributeType(attributeDataSources, idName, idColumn, Attributes.ID_NAME);
resetAttributeType(attributeDataSources, weightName, weightColumn, Attributes.WEIGHT_NAME);
// read data
FileDataRowReader reader = new FileDataRowReader(new DataRowFactory(dataRowType, decimalPointCharacter),
attributeDataSources, sampleRatio, maxLines, separatorRegExpr, comments, useQuotes, '"', '\\', trimLines,
skipErrorLines, encoding, RandomGenerator.getGlobalRandomGenerator());
if (firstRowAsColumnNames) {
reader.skipLine();
}
AttributeSet attributeSet = new AttributeSet(new AttributeDataSources(attributeDataSources, file, encoding));
// create table and example set
ExampleTable table = new MemoryExampleTable(attributeSet.getAllAttributes(), reader);
ExampleSet result = table.createExampleSet(attributeSet);
return result;
}
示例15: run
import java.nio.charset.Charset; //导入依赖的package包/类
public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream stream = context.getResponseDataStream();
String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
body = "Modified via setResponseDataStream(): " + body;
context.setResponseDataStream(new ByteArrayInputStream(body.getBytes("UTF-8")));
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
开发者ID:spring-cloud-samples,项目名称:sample-zuul-filters,代码行数:14,代码来源:ModifyResponseDataStreamFilter.java