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


Java IOUtils类代码示例

本文整理汇总了Java中org.apache.commons.io.IOUtils的典型用法代码示例。如果您正苦于以下问题:Java IOUtils类的具体用法?Java IOUtils怎么用?Java IOUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


IOUtils类属于org.apache.commons.io包,在下文中一共展示了IOUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getMapFromXML

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is =  IOUtils.toInputStream(xmlString);
        Document document = builder.parse(is);
        //获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, Object> map = new HashMap<String, Object>();
        int i=0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if(node instanceof Element){
                map.put(node.getNodeName(),node.getTextContent());
            }
            i++;
        }
        return map;

    }
 
开发者ID:1991wangliang,项目名称:pay,代码行数:23,代码来源:XMLParser.java

示例2: doHandle

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
public void doHandle(final InputStream inStream, final OutputStream outStream) throws Exception {

        try {
            final JsonObject inputJson = SerializationUtil.parseAsJsonElement(IOUtils.toString(inStream, Charset.defaultCharset())).getAsJsonObject();

            final AbstractApiAction apiAction = instantiateAction(inputJson.getAsJsonPrimitive("action").getAsString());

            final UserInfo userInfo = new UserInfo(inputJson.getAsJsonPrimitive("uid").getAsString(), inputJson.getAsJsonPrimitive("groups").getAsString());

            final AbstractApiResponse responseObject = apiAction.getType() != null ?
                    apiAction.handleGeneric((IntegrationRequestBody) SerializationUtil.fromJson(inputJson.getAsJsonObject("body"), apiAction.getType()), userInfo) :
                    apiAction.handleGeneric(null, userInfo);

            if (responseObject != null) {
                IOUtils.write(responseObject.toJson(), outStream, Charset.defaultCharset());
            }
        } catch (final Exception e) {
            ExceptionHandler.processException(e);
        }
    }
 
开发者ID:BackendButters,项目名称:AwsCommons,代码行数:21,代码来源:AbstractLambdaRouter.java

示例3: setUp

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
  // resource file
  this.jsonResource = "org/apache/geode/security/templates/security.json";
  InputStream inputStream = ClassLoader.getSystemResourceAsStream(this.jsonResource);

  assertThat(inputStream).isNotNull();

  // non-resource file
  this.jsonFile = new File(temporaryFolder.getRoot(), "security.json");
  IOUtils.copy(inputStream, new FileOutputStream(this.jsonFile));

  // string
  this.json = FileUtils.readFileToString(this.jsonFile, "UTF-8");
  this.exampleSecurityManager = new ExampleSecurityManager();
}
 
开发者ID:ampool,项目名称:monarch,代码行数:17,代码来源:ExampleSecurityManagerTest.java

示例4: doPost

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@Override
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("application/json");
	response.setCharacterEncoding("utf-8");

	PrintWriter out = response.getWriter();

	String rawContent = IOUtils.toString(request.getReader());
	log.debug(String.format("request content: %s", rawContent));

	out.print(goodsDAO.findById(1));
}
 
开发者ID:MsBuggy,项目名称:AnyMall,代码行数:14,代码来源:GoodsCtrl.java

示例5: download

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
/**
 * 从hadoop中下载文件
 *
 * @param taskName
 * @param filePath
 */
public static void download(String taskName, String filePath, boolean existDelete) {
    File file = new File(filePath);
    if (file.exists()) {
        if (existDelete) {
            file.deleteOnExit();
        } else {
            return;
        }
    }
    String hadoopAddress = propertyConfig.getProperty("sqoop.task." + taskName + ".tolink.linkConfig.uri");
    String itemmodels = propertyConfig.getProperty("sqoop.task." + taskName + ".recommend.itemmodels");
    try {
        DistributedFileSystem distributedFileSystem = distributedFileSystem(hadoopAddress);
        FSDataInputStream fsDataInputStream = distributedFileSystem.open(new Path(itemmodels));
        byte[] bs = new byte[fsDataInputStream.available()];
        fsDataInputStream.read(bs);
        log.info(new String(bs));

        FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
        IOUtils.write(bs, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    } catch (IOException e) {
        log.error(e);
    }
}
 
开发者ID:babymm,项目名称:mmsns,代码行数:32,代码来源:HadoopUtil.java

示例6: getFlowContent

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@Override
public synchronized byte[] getFlowContent(final String bucketId, final String flowId, final int version) throws FlowPersistenceException {
    final File snapshotFile = getSnapshotFile(bucketId, flowId, version);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Retrieving snapshot with filename {}", new Object[] {snapshotFile.getAbsolutePath()});
    }

    if (!snapshotFile.exists()) {
        return null;
    }

    try (final InputStream in = new FileInputStream(snapshotFile)){
        return IOUtils.toByteArray(in);
    } catch (IOException e) {
        throw new FlowPersistenceException("Error reading snapshot file: " + snapshotFile.getAbsolutePath(), e);
    }
}
 
开发者ID:apache,项目名称:nifi-registry,代码行数:18,代码来源:FileSystemFlowPersistenceProvider.java

示例7: ReactViewResolver

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
public ReactViewResolver()
{
    final ClassLoader classLoader = this.getClass().getClassLoader();

    try
    {
        template = new BaseTemplate(
            IOUtils.toString(
                classLoader.getResourceAsStream(TEMPLATE_RESOURCE),
                BaseTemplate.UTF_8
            )
        );
    }
    catch (IOException e)
    {
        throw new ExampleException(e);
    }
}
 
开发者ID:fforw,项目名称:spring-react-example,代码行数:19,代码来源:ReactViewResolver.java

示例8: testCryptomatorInteroperability_longNames_Tests

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
/**
 * Create long file/folder with Cryptomator, read with Cyberduck
 */
@Test
public void testCryptomatorInteroperability_longNames_Tests() throws Exception {
    // create folder
    final java.nio.file.Path targetFolder = cryptoFileSystem.getPath("/", new AlphanumericRandomStringService().random());
    Files.createDirectory(targetFolder);
    // create file and write some random content
    java.nio.file.Path targetFile = targetFolder.resolve(new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(20);
    Files.write(targetFile, content);

    // read with Cyberduck and compare
    final Host host = new Host(new SFTPProtocol(), "localhost", PORT_NUMBER, new Credentials("empty", "empty"));
    final SFTPSession session = new SFTPSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new SFTPHomeDirectoryService(session).find();
    final Path vault = new Path(home, "vault", EnumSet.of(Path.Type.directory));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore()).load(session, new DisabledPasswordCallback() {
        @Override
        public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException {
            return new VaultCredentials(passphrase);
        }
    });
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    Path p = new Path(new Path(vault, targetFolder.getFileName().toString(), EnumSet.of(Path.Type.directory)), targetFile.getFileName().toString(), EnumSet.of(Path.Type.file));
    final InputStream read = new CryptoReadFeature(session, new SFTPReadFeature(session), cryptomator).read(p, new TransferStatus(), new DisabledConnectionCallback());
    final byte[] readContent = new byte[content.length];
    IOUtils.readFully(read, readContent);
    assertArrayEquals(content, readContent);
    session.close();
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:35,代码来源:SFTPCryptomatorInteroperabilityTest.java

示例9: getLatestRun

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@Override
public JobRunInfo getLatestRun(String jobType) throws Exception {
  String path = String.format("%s/job/%s/latestrun", zkPath,
      jobType);
  ensureZkPathExists(path);
  byte[] data = ZkClient.getClient().getData().forPath(path);
  if (data != null && data.length > 0) {
    try {
      return mapper.readValue(IOUtils.toString(data, "UTF-8"), JobRunInfo.class);
    } catch (Exception e) {
      logger.error("Fail to read last run. Error {}", ExceptionUtils.getRootCauseMessage(e));
      return null;
    }
  } else {
    return null;
  }
}
 
开发者ID:pinterest,项目名称:soundwave,代码行数:18,代码来源:ZkJobInfoStore.java

示例10: getWorkerXml

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
Manager getWorkerXml(final String balancerManagerContent) {
    Manager manager;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Manager.class);
        Unmarshaller unmarshal = jaxbContext.createUnmarshaller();
        manager = (Manager) unmarshal.unmarshal(IOUtils.toInputStream(balancerManagerContent));
        List<Manager.Balancer> balancers = manager.getBalancers();
        for (Manager.Balancer balancer : balancers) {
            LOGGER.info(balancer.getName());
            List<Manager.Balancer.Worker> balancer_workers = balancer.getWorkers();
            for (Manager.Balancer.Worker worker : balancer_workers) {
                LOGGER.info(worker.getName() + " " + worker.getRoute());
            }
        }
    } catch (JAXBException e) {
        LOGGER.error(e.toString());
        throw new ApplicationException("Failed to Parsing the Balancer Manager XML ", e);
    }
    return manager;
}
 
开发者ID:cerner,项目名称:jwala,代码行数:21,代码来源:BalancerManagerXmlParser.java

示例11: compile

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@Override
public String compile() {
    try {

        final ProcessBuilder pb = new ProcessBuilder("/bin/sh", getScriptFile());
        pb.directory(new File(System.getProperty("user.dir")));
        final Process p = pb.start();
        p.waitFor();
        String sb = IOUtils.toString(p.getErrorStream(), "UTF-8");
        if (!"".equals(sb)) {
            return sb;
        }
        return "Completed.";
    } catch (Exception ex) {
        Logger.getLogger(MacCompiler.class.getName()).log(Level.SEVERE, null, ex);
        return ex.getMessage();
    }

}
 
开发者ID:CognizantQAHub,项目名称:Cognizant-Intelligent-Test-Scripter,代码行数:20,代码来源:MacCompiler.java

示例12: getProcessDefinitionImage

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@RequestMapping(value = "/process-definition/{processDefinitionId}/image", method = RequestMethod.GET, name="流程定义流程图")
public ResponseEntity<byte[]> getProcessDefinitionImage(@PathVariable String processDefinitionId) {
	ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId);
	InputStream imageStream = repositoryService.getProcessDiagram(processDefinition.getId());

	if (imageStream != null) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentType(MediaType.IMAGE_PNG);
		try {
			return new ResponseEntity<byte[]>(IOUtils.toByteArray(imageStream), responseHeaders,HttpStatus.OK);
		} catch (Exception e) {
			throw new FlowableException("Error reading image stream", e);
		}
	} else {
		throw new FlowableIllegalArgumentException("Process definition with id '" + processDefinition.getId()+ "' has no image.");
	}
}
 
开发者ID:wengwh,项目名称:plumdo-work,代码行数:18,代码来源:ProcessDefinitionImageResource.java

示例13: resolveUsernameFromExternalGroovyScript

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
private String resolveUsernameFromExternalGroovyScript(final Principal principal, final Service service) {
    try {
        LOGGER.debug("Found inline groovy script to execute");
        final String script = IOUtils.toString(ResourceUtils.getResourceFrom(this.groovyScript).getInputStream(), StandardCharsets.UTF_8);

        final Object result = getGroovyAttributeValue(principal, script);
        if (result != null) {
            LOGGER.debug("Found username [{}] from script [{}]", result, this.groovyScript);
            return result.toString();
        }
    } catch (final IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    LOGGER.warn("Groovy script [{}] returned no value for username attribute. Fallback to default [{}]",
            this.groovyScript, principal.getId());
    return principal.getId();
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:19,代码来源:GroovyRegisteredServiceUsernameProvider.java

示例14: testWriteUnknownLength

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
@Test
public void testWriteUnknownLength() throws Exception {
    final OneDriveBufferWriteFeature feature = new OneDriveBufferWriteFeature(session);
    final Path container = new OneDriveHomeFinderFeature(session).find();
    final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    new StreamCopier(status, status).transfer(in, out);
    in.close();
    out.flush();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new OneDriveReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:24,代码来源:OneDriveBufferWriteFeatureTest.java

示例15: getAllQuery

import org.apache.commons.io.IOUtils; //导入依赖的package包/类
private String getAllQuery() {
    URL queryLoc = getClass().getResource(getClass().getSimpleName() + "_getAll.sql");
    try {
        return IOUtils.toString(queryLoc, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:cloudwall,项目名称:libcwfincore,代码行数:9,代码来源:JdbiProductEntityDao.java


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