本文整理汇总了Java中java.nio.charset.StandardCharsets.UTF_8属性的典型用法代码示例。如果您正苦于以下问题:Java StandardCharsets.UTF_8属性的具体用法?Java StandardCharsets.UTF_8怎么用?Java StandardCharsets.UTF_8使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类java.nio.charset.StandardCharsets
的用法示例。
在下文中一共展示了StandardCharsets.UTF_8属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: build
public ApiGatewayResponse build() {
String body = null;
if (rawBody != null) {
body = rawBody;
} else if (objectBody != null) {
try {
body = objectMapper.writeValueAsString(objectBody);
} catch (JsonProcessingException e) {
LOG.error("failed to serialize object", e);
throw new RuntimeException(e);
}
} else if (binaryBody != null) {
body = new String(Base64.getEncoder().encode(binaryBody), StandardCharsets.UTF_8);
}
return new ApiGatewayResponse(statusCode, body, headers, base64Encoded);
}
示例2: resolve
/**
* @param type the ec2 hostname type to discover.
* @return the appropriate host resolved from ec2 meta-data, or null if it cannot be obtained.
* @see CustomNameResolver#resolveIfPossible(String)
*/
@SuppressForbidden(reason = "We call getInputStream in doPrivileged and provide SocketPermission")
public InetAddress[] resolve(Ec2HostnameType type) throws IOException {
InputStream in = null;
String metadataUrl = AwsEc2ServiceImpl.EC2_METADATA_URL + type.ec2Name;
try {
URL url = new URL(metadataUrl);
logger.debug("obtaining ec2 hostname from ec2 meta-data url {}", url);
URLConnection urlConnection = SocketAccess.doPrivilegedIOException(url::openConnection);
urlConnection.setConnectTimeout(2000);
in = SocketAccess.doPrivilegedIOException(urlConnection::getInputStream);
BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
String metadataResult = urlReader.readLine();
if (metadataResult == null || metadataResult.length() == 0) {
throw new IOException("no gce metadata returned from [" + url + "] for [" + type.configName + "]");
}
// only one address: because we explicitly ask for only one via the Ec2HostnameType
return new InetAddress[] { InetAddress.getByName(metadataResult) };
} catch (IOException e) {
throw new IOException("IOException caught when fetching InetAddress from [" + metadataUrl + "]", e);
} finally {
IOUtils.closeWhileHandlingException(in);
}
}
示例3: main
/**
* Početna točka programa CijeliBrojeviKonzola. Parametri komandne linije se ne koriste.
* @param args Parametri komandne linije.
* @throws IOException Problem s čitanjem s konzole.
*/
public static void main(String[] args) throws IOException {
BufferedReader ulaz = new BufferedReader(new InputStreamReader(System.in,
StandardCharsets.UTF_8));
while (true) {
System.out.print("Unesite broj> ");
String brojString = ulaz.readLine();
if(brojString.trim().equals("quit")) {
System.exit(0);
}
int broj = 0;
try {
broj = Integer.parseInt(brojString);
} catch (NumberFormatException e) {
System.out.println("Neispravan unos!");
continue;
}
System.out.print("Paran: " + (CijeliBrojevi.jeParan(broj) ? "DA" : "NE") + ", ");
System.out.print("neparan: " + (CijeliBrojevi.jeNeparan(broj) ? "DA" : "NE") + ", ");
System.out.println("prim: " + (CijeliBrojevi.jeProst(broj) ? "DA" : "NE"));
}
}
示例4: process
@Override
public void process(final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
final HttpResponseAttachment.Builder builder = create("Response")
.withResponseCode(response.getStatusLine().getStatusCode());
Stream.of(response.getAllHeaders())
.forEach(header -> builder.withHeader(header.getName(), header.getValue()));
final ByteArrayOutputStream os = new ByteArrayOutputStream();
response.getEntity().writeTo(os);
final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
builder.withBody(body);
final HttpResponseAttachment responseAttachment = builder.build();
processor.addAttachment(responseAttachment, renderer);
}
示例5: readResponse
public static String readResponse(InputStream stream) throws IOException {
byte[] data = new byte[100];
int read;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((read = stream.read(data)) != -1) {
out.write(data, 0, read);
}
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
示例6: charsetFrom
/**
* Get the Charset from the Content-encoding header. Defaults to
* UTF_8
*/
public static Charset charsetFrom(HttpHeaders headers) {
String encoding = headers.firstValue("Content-encoding")
.orElse("UTF_8");
try {
return Charset.forName(encoding);
} catch (IllegalArgumentException e) {
return StandardCharsets.UTF_8;
}
}
示例7: ProguardFileParser
ProguardFileParser(Path path) throws IOException {
this.path = path;
contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
baseDirectory = path.getParent();
if (baseDirectory == null) {
// path parent can be null only if it's root dir or if its a one element path relative to
// current directory.
baseDirectory = Paths.get(".");
}
}
示例8: getStopWords
/**
* Fills stopwords collection from stopwords file.
*
* @throws IOException
* On error with reading a file.
*/
private void getStopWords() throws IOException {
stopWords = new HashSet<String>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
stopwords, StandardCharsets.UTF_8))) {
String word = reader.readLine().toLowerCase();
while (word != null && !word.isEmpty()) {
stopWords.add(word);
word = reader.readLine();
}
}
}
示例9: read
/**
* Reads a cached graph and parses it to the internal graph array data structure.
*
* @param graphSize the number of nodes in the graph
* @param progressUpdater a {@link ProgressUpdater} to notify interested parties on progress updates
* @return internal graph array data structure from cache file
* @throws IOException if the cache file cannot be read
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") // Unique instance per iteration
public int[][] read(final int graphSize, final ProgressUpdater progressUpdater) throws IOException {
final int[][] graph = new int[graphSize][];
try (BufferedReader cache = new BufferedReader(new InputStreamReader(
new FileInputStream(file), StandardCharsets.UTF_8))) {
String node;
int nodeIndex = 0;
while ((node = cache.readLine()) != null) {
if (nodeIndex % PROGRESS_UPDATE_INTERVAL == 0) {
progressUpdater.updateProgress(
PROGRESS_TOTAL * nodeIndex / graphSize,
"Restoring graph from cache...");
}
final StringTokenizer nodeTokenizer = new StringTokenizer(node, NODE_VALUE_SEPARATOR);
graph[nodeIndex] = new int[nodeTokenizer.countTokens()];
int valueIndex = 0;
while (nodeTokenizer.hasMoreTokens()) {
graph[nodeIndex][valueIndex] = Integer.parseInt(nodeTokenizer.nextToken());
valueIndex++;
}
nodeIndex++;
}
}
return graph;
}
示例10: testDigest
@Test
public void testDigest() throws IOException, NoSuchAlgorithmException {
final URL redisChart = Thread.currentThread().getContextClassLoader().getResource("redis-0.5.1/redis-0.5.1.tgz");
assertNotNull(redisChart);
final URL digest = Thread.currentThread().getContextClassLoader().getResource("redis-0.5.1/digest");
assertNotNull(digest);
assertTrue(digest.getProtocol().equals("file"));
String expectedDigest = null;
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(digest.openStream(), StandardCharsets.UTF_8))) {
assertNotNull(reader);
expectedDigest = reader.readLine();
assertNotNull(expectedDigest);
expectedDigest = expectedDigest.toUpperCase();
}
final MessageDigest md = MessageDigest.getInstance("SHA-256");
assertNotNull(md);
ByteBuffer buffer = null;
try (final InputStream rawInputStream = redisChart.openStream();
final BufferedInputStream stream = rawInputStream instanceof BufferedInputStream ? (BufferedInputStream)rawInputStream : new BufferedInputStream(rawInputStream)) {
assertNotNull(rawInputStream);
assertNotNull(stream);
buffer = readByteBuffer(stream);
}
assertNotNull(buffer);
md.update(buffer);
assertEquals(expectedDigest, DatatypeConverter.printHexBinary(md.digest()));
}
示例11: decodeBasicAuth
private String[] decodeBasicAuth(String authHeader) {
String basicAuth;
try {
basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
} catch (IllegalArgumentException | IndexOutOfBoundsException e) {
throw new BadCredentialsException("Failed to decode basic authentication token");
}
int delim = basicAuth.indexOf(":");
if (delim == -1) {
throw new BadCredentialsException("Failed to decode basic authentication token");
}
return new String[] { basicAuth.substring(0, delim), basicAuth.substring(delim + 1) };
}
示例12: write
/**
* @throws IOException if any file operation fails with an IO exception
*/
public void write(final Map<TopicPartition, Long> offsets) throws IOException {
synchronized (lock) {
// write to temp file and then swap with the existing file
final File temp = new File(file.getAbsolutePath() + ".tmp");
final FileOutputStream fileOutputStream = new FileOutputStream(temp);
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8))) {
writeIntLine(writer, VERSION);
writeIntLine(writer, offsets.size());
for (final Map.Entry<TopicPartition, Long> entry : offsets.entrySet()) {
writeEntry(writer, entry.getKey(), entry.getValue());
}
writer.flush();
fileOutputStream.getFD().sync();
}
Utils.atomicMoveWithFallback(temp.toPath(), file.toPath());
}
}
示例13: updateMavenFile
private void updateMavenFile(String source, IProject project) throws CoreException {
try{
IFile destinationFile = project.getFile(source);
java.nio.file.Path path = Paths.get(destinationFile.getLocationURI());
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll(TEMPLATE_PROJECT_NAME, project.getName());
Files.write(path, content.getBytes(charset));
} catch (IOException exception) {
logger.debug("Could not change the group and artifact name");
throw new CoreException(new MultiStatus(Activator.PLUGIN_ID, 100, "Could not change the group and artifact name", exception));
}
}
示例14: main
public static void main(String[] args) throws IOException {
String fileName = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)))
{fileName = reader.readLine();}
String content = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
String[] words = content.split(" ");
StringBuilder result = getLine(words);
System.out.println(result.toString());
}
示例15: readInput
private static String readInput(InputStream stream) throws IOException {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
final StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}