本文整理汇总了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;
}
示例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);
}
}
示例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();
}
示例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));
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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();
}
示例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;
}
}
示例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;
}
示例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();
}
}
示例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.");
}
}
示例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();
}
示例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());
}
示例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);
}
}