当前位置: 首页>>代码示例>>Java>>正文


Java StandardCharsets.UTF_8属性代码示例

本文整理汇总了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);
}
 
开发者ID:lambdacult,项目名称:spark-examples,代码行数:16,代码来源:ApiGatewayResponse.java

示例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);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:29,代码来源:Ec2NameResolver.java

示例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"));
	}
}
 
开发者ID:fgulan,项目名称:java-course,代码行数:27,代码来源:CijeliBrojeviKonzola.java

示例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);
}
 
开发者ID:allure-framework,项目名称:allure-java,代码行数:19,代码来源:AllureHttpClientResponse.java

示例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);
    }
 
开发者ID:networknt,项目名称:light-session-4j,代码行数:10,代码来源:HttpClientUtils.java

示例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;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:Utils.java

示例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(".");
  }
}
 
开发者ID:inferjay,项目名称:r8,代码行数:10,代码来源:ProguardConfigurationParser.java

示例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();
        }
    }
}
 
开发者ID:fgulan,项目名称:java-course,代码行数:18,代码来源:SearchEngine.java

示例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;
}
 
开发者ID:ProgrammingLife2017,项目名称:hygene,代码行数:38,代码来源:GraphArrayFile.java

示例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()));
}
 
开发者ID:microbean,项目名称:microbean-helm,代码行数:27,代码来源:TestDigest.java

示例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) };
}
 
开发者ID:revinate,项目名称:grpc-spring-security-demo,代码行数:15,代码来源:BasicAuthenticationInterceptor.java

示例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());
    }
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:25,代码来源:OffsetCheckpoint.java

示例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));
	}
}
 
开发者ID:capitalone,项目名称:Hydrograph,代码行数:13,代码来源:ProjectStructureCreator.java

示例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());
}
 
开发者ID:avedensky,项目名称:JavaRushTasks,代码行数:11,代码来源:Solution.java

示例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();
    }
}
 
开发者ID:mozilla-mobile,项目名称:firefox-tv,代码行数:12,代码来源:HostScreencapScreenshotStrategy.java


注:本文中的java.nio.charset.StandardCharsets.UTF_8属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。