本文整理匯總了Java中org.apache.commons.compress.utils.IOUtils類的典型用法代碼示例。如果您正苦於以下問題:Java IOUtils類的具體用法?Java IOUtils怎麽用?Java IOUtils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
IOUtils類屬於org.apache.commons.compress.utils包,在下文中一共展示了IOUtils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: makeOnlyUnZip
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
public static void makeOnlyUnZip() throws ArchiveException, IOException{
final InputStream is = new FileInputStream("D:/中文名字.zip");
ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);
ZipArchiveEntry entry = entry = (ZipArchiveEntry) in.getNextEntry();
String dir = "D:/cnname";
File filedir = new File(dir);
if(!filedir.exists()){
filedir.mkdir();
}
// OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
OutputStream out = new FileOutputStream(new File(filedir, entry.getName()));
IOUtils.copy(in, out);
out.close();
in.close();
}
示例2: addFileToTarGz
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/**
* Recursively adds a directory to a .tar.gz. Adapted from http://stackoverflow.com/questions/13461393/compress-directory-to-tar-gz-with-commons-compress
*
* @param tOut The .tar.gz to add the directory to
* @param path The location of the folders and files to add
* @param base The base path of entry in the .tar.gz
* @throws IOException Any exceptions thrown during tar creation
*/
private void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base) throws IOException {
File f = new File(path);
String entryName = base + f.getName();
TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
tOut.putArchiveEntry(tarEntry);
Platform.runLater(() -> fileLabel.setText("Processing " + f.getPath()));
if (f.isFile()) {
FileInputStream fin = new FileInputStream(f);
IOUtils.copy(fin, tOut);
fin.close();
tOut.closeArchiveEntry();
} else {
tOut.closeArchiveEntry();
File[] children = f.listFiles();
if (children != null) {
for (File child : children) {
addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/");
}
}
}
}
示例3: downloadFile
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/** 문자열 path를 가지고 파일을 다운 받아 바이트 배열로 바꿔주는 메서드.
* https://stackoverflow.com/questions/2295221/java-net-url-read-stream-to-byte 소스 코드 참고
* @param path
* @return
*/
public static byte[] downloadFile(String path)
{
try {
URL url = new URL(path);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
conn.connect();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);
return baos.toByteArray();
}
catch (IOException e)
{
return null;
}
}
示例4: addTarGzipToArchive
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/**
* given tar.gz file will be copied to this tar.gz file.
* all files will be transferred to new tar.gz file one by one.
* original directory structure will be kept intact
*
* @param tarGzipFile the archive file to be copied to the new archive
*/
public boolean addTarGzipToArchive(String tarGzipFile) {
try {
// construct input stream
InputStream fin = Files.newInputStream(Paths.get(tarGzipFile));
BufferedInputStream in = new BufferedInputStream(fin);
GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzIn);
// copy the existing entries from source gzip file
ArchiveEntry nextEntry;
while ((nextEntry = tarInputStream.getNextEntry()) != null) {
tarOutputStream.putArchiveEntry(nextEntry);
IOUtils.copy(tarInputStream, tarOutputStream);
tarOutputStream.closeArchiveEntry();
}
tarInputStream.close();
return true;
} catch (IOException ioe) {
LOG.log(Level.SEVERE, "Archive File can not be added: " + tarGzipFile, ioe);
return false;
}
}
示例5: addFileToArchive
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/**
* add one file to tar.gz file
*
* @param file file to be added to the tar.gz
*/
public boolean addFileToArchive(File file, String dirPrefixForTar) {
try {
String filePathInTar = dirPrefixForTar + file.getName();
TarArchiveEntry entry = new TarArchiveEntry(file, filePathInTar);
entry.setSize(file.length());
tarOutputStream.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file), tarOutputStream);
tarOutputStream.closeArchiveEntry();
return true;
} catch (IOException e) {
LOG.log(Level.SEVERE, "File can not be added: " + file.getName(), e);
return false;
}
}
示例6: addFileToTarGz
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/**
* This function copies a given file to the zip file
*
* @param tarArchiveOutputStream tar output stream of the zip file
* @param file the file to insert to the zar file
*
* @throws IOException
*/
private static void addFileToTarGz(TarArchiveOutputStream tarArchiveOutputStream, File file)
throws IOException
{
String entryName = file.getName();
TarArchiveEntry tarEntry = new TarArchiveEntry(file, entryName);
tarArchiveOutputStream.putArchiveEntry(tarEntry);
if (file.isFile()) {
try (FileInputStream input = new FileInputStream(file))
{
IOUtils.copy(input, tarArchiveOutputStream);
}
tarArchiveOutputStream.closeArchiveEntry();
} else {//Directory
System.out.println("The directory which need to be packed to tar folder cannot contain other directories");
}
}
示例7: publish
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
public void publish(BrokerStats brokerStats) throws IOException {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream, null);
avroEventWriter.write(brokerStats, binaryEncoder);
binaryEncoder.flush();
IOUtils.closeQuietly(stream);
String key = brokerStats.getName() + "_" + System.currentTimeMillis();
int numPartitions = kafkaProducer.partitionsFor(destTopic).size();
int partition = brokerStats.getId() % numPartitions;
Future<RecordMetadata> future = kafkaProducer.send(
new ProducerRecord(destTopic, partition, key.getBytes(), stream.toByteArray()));
future.get();
OpenTsdbMetricConverter.incr("kafka.stats.collector.success", 1, "host=" + HOSTNAME);
} catch (Exception e) {
LOG.error("Failure in publish stats", e);
OpenTsdbMetricConverter.incr("kafka.stats.collector.failure", 1, "host=" + HOSTNAME);
throw new RuntimeException("Avro serialization failure", e);
}
}
示例8: sendMessage
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
public synchronized void sendMessage(String clusterName, String message) {
int numRetries = 0;
while (numRetries < MAX_RETRIES) {
try {
long timestamp = System.currentTimeMillis();
OperatorAction operatorAction = new OperatorAction(timestamp, clusterName, message);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream, null);
avroWriter.write(operatorAction, binaryEncoder);
binaryEncoder.flush();
IOUtils.closeQuietly(stream);
String key = "" + System.currentTimeMillis();
ProducerRecord producerRecord =
new ProducerRecord(topic, key.getBytes(), stream.toByteArray());
Future<RecordMetadata> future = kafkaProducer.send(producerRecord);
future.get();
LOG.info("Send an message {} to action report : ", message);
break;
} catch (Exception e) {
LOG.error("Failed to publish report message {}: {}", clusterName, message, e);
numRetries++;
}
}
}
示例9: downloadZipAndExtract
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
protected static void downloadZipAndExtract(final String url, final File targetDirectory) {
download(url, inputStream -> {
try {
final byte[] bytes = IOUtils.toByteArray(inputStream);
try (final ZipFile zipFile = new ZipFile(new SeekableInMemoryByteChannel(bytes))) {
final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
while (entries.hasMoreElements()) {
final ZipArchiveEntry entry = entries.nextElement();
final File file = new File(targetDirectory, entry.getName());
if (entry.isDirectory()) {
file.mkdir();
continue;
}
try (final OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(file))) {
IOUtils.copy(zipFile.getInputStream(entry), outputStream);
}
}
}
} catch (final IOException exception) {
throw new RuntimeException(exception);
}
});
}
示例10: testHandle
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/**
* Test of handle method, of class ZipContentParser.
*/
@Test
public void testHandle() {
System.out.println("handle");
try {
EntityManager manager = new PersistenceProvider().get();
if(!manager.getTransaction().isActive()) {
manager.getTransaction().begin();
}
manager.persist(new Modification("ZipContentParserTest.mod",31));
manager.getTransaction().commit();
IOUtils.copy(getClass().getResourceAsStream("/test.zip"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/a.zip")));
List <ProcessTask> result = get().handle(manager);
Assert.assertTrue(
"result is not of correct type",
result instanceof List<?>
);
Assert.assertEquals(
"Unexpected follow-ups",
0,
result.size()
);
} catch(Exception ex) {
Assert.fail(ex.getMessage());
}
}
示例11: unpackTarArchiveEntry
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
public static void unpackTarArchiveEntry(TarArchiveInputStream tarStream, TarArchiveEntry entry, File outputDirectory) throws IOException {
String fileName = entry.getName().substring(entry.getName().indexOf("/"), entry.getName().length());
File outputFile = new File(outputDirectory,fileName);
if (entry.isDirectory()) {
if (!outputFile.exists()) {
if (!outputFile.mkdirs()) {
throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
}
}
unpackTar(tarStream, entry.getDirectoryEntries(), outputFile);
return;
}
OutputStream outputFileStream = new FileOutputStream(outputFile);
IOUtils.copy(tarStream, outputFileStream);
outputFileStream.close();
}
示例12: gZip
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
public static byte[] gZip(byte[] data) throws IOException
{
byte[] ret = null;
ByteArrayOutputStream bos = null;
GZIPOutputStream gzip = null;
try
{
bos = new ByteArrayOutputStream();
gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
ret = bos.toByteArray();
} finally
{
IOUtils.closeQuietly(gzip);
IOUtils.closeQuietly(bos);
}
return ret;
}
示例13: run
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
@Override
public void run() {
try {
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line;
final String[] errors = new String[3];
int counter = 0;
while ((line = br.readLine()) != null) {
Log.v(TAG, line);
errors[counter++ % 3] = line;
}
if (er != null)
er.onError(errors);
} catch (final IOException ioe) {
ioe.printStackTrace();
} finally {
IOUtils.closeQuietly(is);
}
}
示例14: onPause
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
@Override
protected void onPause() {
super.onPause();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED &&
!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE))
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
0);
// save file
OutputStream f = null;
try {
f = new FileOutputStream(Utils.getBitcoinConf(this));
IOUtils.copy(new ByteArrayInputStream(((EditText) findViewById(R.id.editText))
.getText().toString().getBytes("UTF-8")), f);
} catch (final IOException e) {
Log.i(TAG, e.getMessage());
} finally {
IOUtils.closeQuietly(f);
}
}
示例15: unZipToFolder
import org.apache.commons.compress.utils.IOUtils; //導入依賴的package包/類
/**
* 把一個ZIP文件解壓到一個指定的目錄中
* @param zipfilename ZIP文件抽象地址
* @param outputdir 目錄絕對地址
*/
public static void unZipToFolder(String zipfilename, String outputdir) throws IOException {
File zipfile = new File(zipfilename);
if (zipfile.exists()) {
outputdir = outputdir + File.separator;
FileUtils.forceMkdir(new File(outputdir));
ZipFile zf = new ZipFile(zipfile, "UTF-8");
Enumeration zipArchiveEntrys = zf.getEntries();
while (zipArchiveEntrys.hasMoreElements()) {
ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
if (zipArchiveEntry.isDirectory()) {
FileUtils.forceMkdir(new File(outputdir + zipArchiveEntry.getName() + File.separator));
} else {
IOUtils.copy(zf.getInputStream(zipArchiveEntry), FileUtils.openOutputStream(new File(outputdir + zipArchiveEntry.getName())));
}
}
} else {
throw new IOException("指定的解壓文件不存在:\t" + zipfilename);
}
}