导航:首页 > 文件处理 > java文本压缩

java文本压缩

发布时间:2022-01-17 15:43:07

1. java如何将很长的字符串存储为压缩文件

String str = ""; int length = str.length(); List<Integer> index = new ArrayList<Integer>(); for (int i = 0; i < length - 1; i++) { if(str.charAt(i) != str.charAt(i + 1)){ index.add(i); } } if(str.charAt(length - 2) != str.charAt(length - 1)){ index.add(length - 1); } int start = 0; StringBuffer result = new StringBuffer(); for (int i = 0; i < index.size(); i++) { int end = index.get(i) + 1; if(i != 0){ start = index.get(i - 1) + 1; } String temp = str.substring(start, end); result.append(temp.charAt(0)).append(end - start); } System.out.println(result.toString());最终结果是:a6s4c5d7w1s1a3s1d1c1a1s1

2. java读取文件内容并生成压缩BCD格式

您的排序与zip排序不一样。
所以第一步应该得到所有名称,然后再按照新的顺序来读

如果只是解压到某处,新的顺序一点用处都没有!

3. Java 字符串压缩与解压

给你提供个思想
首先你这不是物理上的压缩,也就是说它是一个逻辑上的我们认同上的压缩。
你需要写一个算法来对你所要处理的数据进行统计,然后按照算法来改变结果。
最后达到一个后台的虚拟压缩(实际上不是压缩,只是算法)。

4. java 如何将 txt 文件 变成zip压缩文件 求例子!!

这个要用 压缩流类 ZipOutputStream
下面是一个例子 在D盘下有个 名字叫 demo.txt的文件.程序运行后会再D盘下生成一个demo.zip的文件,以下是代码:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipOutputStreamDemo {
public static void main(String args[]) throws IOException {
//定义要压缩的文件 也就是说在D盘里有个 demo.txt 的文件(必须要有,否者会有异常,实际应用中可判断);
File file = new File("d:" + File.separator + "demo.txt");

//定义压缩文件的名称
File zipFile = new File("d:" + File.separator + "demo.zip");

//定义输入文件流
InputStream input = new FileInputStream(file);

//定义压缩输出流
ZipOutputStream zipOut = null;

//实例化压缩输出流,并制定压缩文件的输出路径 就是D盘下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

zipOut.putNextEntry(new ZipEntry(file.getName()));

//设置注释
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();

}
}
希望能帮助楼主,建议楼主多看看JDK文档,设计到文件的输出什么都在JAVA.IO包里,好好看看..
不过楼主要知道,压缩流也是inputstream和outputstream的子类,但是并没有定义在java.io包里,而是以一个工具类的形式出现的,但是在用的时候还是需要java.io包的支持的...

5. 怎样用java快速实现zip文件的压缩解压缩

packagezip;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.util.Enumeration;
importjava.util.zip.CRC32;
importjava.util.zip.CheckedOutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipFile;
importjava.util.zip.ZipOutputStream;
importorg.apache.commons.lang3.StringUtils;
publicclassZipUtil{

/**
*递归压缩文件夹
*@paramsrcRootDir压缩文件夹根目录的子路径
*@paramfile当前递归压缩的文件或目录对象
*@paramzos压缩文件存储对象
*@throwsException
*/
privatestaticvoidzip(StringsrcRootDir,Filefile,ZipOutputStreamzos)throwsException
{
if(file==null)
{
return;
}

//如果是文件,则直接压缩该文件
if(file.isFile())
{
intcount,bufferLen=1024;
bytedata[]=newbyte[bufferLen];

//获取文件相对于压缩文件夹根目录的子路径
StringsubPath=file.getAbsolutePath();
intindex=subPath.indexOf(srcRootDir);
if(index!=-1)
{
subPath=subPath.substring(srcRootDir.length()+File.separator.length());
}
ZipEntryentry=newZipEntry(subPath);
zos.putNextEntry(entry);
BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));
while((count=bis.read(data,0,bufferLen))!=-1)
{
zos.write(data,0,count);
}
bis.close();
zos.closeEntry();
}
//如果是目录,则压缩整个目录
else
{
//压缩目录中的文件或子目录
File[]childFileList=file.listFiles();
for(intn=0;n<childFileList.length;n++)
{
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir,childFileList[n],zos);
}
}
}

/**
*对文件或文件目录进行压缩
*@paramsrcPath要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径
*@paramzipPath压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹
*@paramzipFileName压缩文件名
*@throwsException
*/
publicstaticvoidzip(StringsrcPath,StringzipPath,StringzipFileName)throwsException
{
if(StringUtils.isEmpty(srcPath)||StringUtils.isEmpty(zipPath)||StringUtils.isEmpty(zipFileName))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
CheckedOutputStreamcos=null;
ZipOutputStreamzos=null;
try
{
FilesrcFile=newFile(srcPath);

//判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)
if(srcFile.isDirectory()&&zipPath.indexOf(srcPath)!=-1)
{
thrownewParameterException(ICommonResultCode.INVALID_PARAMETER,".");
}

//判断压缩文件保存的路径是否存在,如果不存在,则创建目录
FilezipDir=newFile(zipPath);
if(!zipDir.exists()||!zipDir.isDirectory())
{
zipDir.mkdirs();
}

//创建压缩文件保存的文件对象
StringzipFilePath=zipPath+File.separator+zipFileName;
FilezipFile=newFile(zipFilePath);
if(zipFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
=newSecurityManager();
securityManager.checkDelete(zipFilePath);
//删除已存在的目标文件
zipFile.delete();
}

cos=newCheckedOutputStream(newFileOutputStream(zipFile),newCRC32());
zos=newZipOutputStream(cos);

//如果只是压缩一个文件,则需要截取该文件的父目录
StringsrcRootDir=srcPath;
if(srcFile.isFile())
{
intindex=srcPath.lastIndexOf(File.separator);
if(index!=-1)
{
srcRootDir=srcPath.substring(0,index);
}
}
//调用递归压缩方法进行目录或文件压缩
zip(srcRootDir,srcFile,zos);
zos.flush();
}
catch(Exceptione)
{
throwe;
}
finally
{
try
{
if(zos!=null)
{
zos.close();
}
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

/**
*解压缩zip包
*@paramzipFilePathzip文件的全路径
*@paramunzipFilePath解压后的文件保存的路径
*@paramincludeZipFileName解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
publicstaticvoinzip(StringzipFilePath,StringunzipFilePath,booleanincludeZipFileName)throwsException
{
if(StringUtils.isEmpty(zipFilePath)||StringUtils.isEmpty(unzipFilePath))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
FilezipFile=newFile(zipFilePath);
//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if(includeZipFileName)
{
StringfileName=zipFile.getName();
if(StringUtils.isNotEmpty(fileName))
{
fileName=fileName.substring(0,fileName.lastIndexOf("."));
}
unzipFilePath=unzipFilePath+File.separator+fileName;
}
//创建解压缩文件保存的路径
FileunzipFileDir=newFile(unzipFilePath);
if(!unzipFileDir.exists()||!unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}

//开始解压
ZipEntryentry=null;
StringentryFilePath=null,entryDirPath=null;
FileentryFile=null,entryDir=null;
intindex=0,count=0,bufferSize=1024;
byte[]buffer=newbyte[bufferSize];
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
ZipFilezip=newZipFile(zipFile);
Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)zip.entries();
//循环对压缩包里的每一个文件进行解压
while(entries.hasMoreElements())
{
entry=entries.nextElement();
//构建压缩包中一个文件解压后保存的文件全路径
entryFilePath=unzipFilePath+File.separator+entry.getName();
//构建解压后保存的文件夹路径
index=entryFilePath.lastIndexOf(File.separator);
if(index!=-1)
{
entryDirPath=entryFilePath.substring(0,index);
}
else
{
entryDirPath="";
}
entryDir=newFile(entryDirPath);
//如果文件夹路径不存在,则创建文件夹
if(!entryDir.exists()||!entryDir.isDirectory())
{
entryDir.mkdirs();
}

//创建解压文件
entryFile=newFile(entryFilePath);
if(entryFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
=newSecurityManager();
securityManager.checkDelete(entryFilePath);
//删除已存在的目标文件
entryFile.delete();
}

//写入文件
bos=newBufferedOutputStream(newFileOutputStream(entryFile));
bis=newBufferedInputStream(zip.getInputStream(entry));
while((count=bis.read(buffer,0,bufferSize))!=-1)
{
bos.write(buffer,0,count);
}
bos.flush();
bos.close();
}
}

publicstaticvoidmain(String[]args)
{
StringzipPath="d:\ziptest\zipPath";
Stringdir="d:\ziptest\rawfiles";
StringzipFileName="test.zip";
try
{
zip(dir,zipPath,zipFileName);
}
catch(Exceptione)
{
e.printStackTrace();
}

StringzipFilePath="D:\ziptest\zipPath\test.zip";
StringunzipFilePath="D:\ziptest\zipPath";
try
{
unzip(zipFilePath,unzipFilePath,true);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}

6. java 如何压缩文件

楼主是说解压了的文件大小只有33.1MB,但是却占了51.2MB的空间吗?
如果是这个意思的话,那我要告诉楼主,首先这个问题和JAVA没有关系,根据你的截图,可以断定你用的是FAT32文件系统。这只是文件存储的形式,很正常。
简单的说,磁盘存储数据的最小单位是簇,比方说你的簇大小为128K,一个簇只能存放一个文件,然后你的一个文件只有16K,它占了这个簇,然后还有112K没有用,是吧。但是那112K就不能再存放其它文件了。如果要存放其它文件,就要占另一个簇。
楼主,懂了吧,这跟簇的大小有关,但是也不是簇越小越好,簇越小,读写性能都有所下降。这是正常现象。如果你非觉得不舒服,那就用NTFS文件系统吧,把压缩打开,就不会有这种情况了,希望对你有帮助

7. 用java实现,压缩字符串,例如aaaawwwwe输出4a5we

publicStringcountChar(Stringstr){
char[]aa=str.toCharArray();
int[]ch=newint[255];//以扩展ascII码的长度定义整型数组,用于计数,比如a出现一次时,ch[97]就加1,附ascII码表http://wenku..com/link?url=QtgixHAgMzyo_Ts_bLburo-qcOX7FAhR8vl96BrPbWA05FAbW-SCCARIZfjIBWxDzi-FmWonFjnoRBKMA8jQ1Wg3FDyG_6NZwbf4SZ4IH4C
for(inti=0;i<aa.length;i++){
chara=aa[i];
ch[a]++;//char型变量用于整型时,java取其ascII码
}
Stringresult="";
//计数完成后遍历ch取计数值
for(inti=0;i<ch.length;i++){
if(ch[i]>0){
result+=ch[i];//取计数值
charc=i;//取ascII码对应的字符
result+=String.valueOf(c);
}
}
returnresult;
}

8. 用java如何实现压缩字符串

package javase1.day02;
/**
* 1)一种字符串压缩算法
* str ="aaaabbccccddeaaa"
* 压缩为:"4a2b4c2d1e3a"
* 原理实现:
* str = "aaaabbccccddeaaa"
*
* c = str.charAt(i)//c是每个字符
* 1) 初始化
* StringBuilder buf = new StringBuilder();
* int count = 0;代表相同的字符个数
* char ch = str.charAt(0);代表正在统计的相同字符'a'
* 2) 从i=1开始迭代每个字符
* c = str.charAt(i);//c是每个当前字符
* 3) 检查当前字符c与被统计ch是否一致
* 如果一致 count++
* 否则(不一致)
* 向缓冲区buf增加count+ch
* count=0,ch=c;
* 3)没有下个字符就结束
* 4)还有字符串吗?回到2)
*
* 2)实现还原算法
* str = "4a2b4c2d1e3a";
* i
*/
public class Demo5 {
public static void main(String[] args) {
String s = comp("aaaawwwwe");
System.out.println(s);
// System.out.println(decomp(s));

}
public static String comp(String str){
int i = 1;
StringBuilder buf = new StringBuilder();
int count = 1;
char ch = str.charAt(0);
for(;;){
char c = i==str.length() ? '\10':str.charAt(i);
if(c==ch){
count++;
}else{
if(count == 1)
buf.append(ch);
else
buf.append(count).append(ch);
count=1;
ch = c;
}
i++;
if(i==str.length()+1){
break;
}
}
return buf.toString();

}
}

9. java 什么算法压缩文件最小

有三种方式实现java压缩:

1、jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称带中文时,出现乱码问题,实现代码如下:
/**
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
* @param sourceDir 如果是目录,eg:D:\\MyEclipse\\first\\testFile,则压缩目录下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,则只压缩本文件
* @param zipFile 最后压缩的文件路径和名称,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath) throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 创建写出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);

String basePath = null;

// 获取目录
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}

zipFile(file, basePath, zos);
}finally {
if(zos != null) {
zos.closeEntry();
zos.close();
}
}

return zipFile;
}
/**
* @param source 源文件
* @param basePath
* @param zos
*/
private void zipFile(File source, String basePath, ZipOutputStream zos)
throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}

InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for(File file : files) {
if(file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
}else {
pathName = file.getPath().substring(basePath.length() + 1);
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) {
zos.write(buf, 0, length);
}
}
}
}finally {
if(is != null) {
is.close();
}
}
}

2、使用org.apache.tools.zip.ZipOutputStream,代码如下,
package net.szh.zip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipCompressor {
static final int BUFFER = 8192;

private File zipFile;

public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}

public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private void compress(File file, ZipOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
System.out.println("压缩:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("压缩:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}

/** 压缩一个目录 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;

File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}

/** 压缩一个文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

3、可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。
package net.szh.zip;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

public class ZipCompressorByAnt {

private File zipFile;

public ZipCompressorByAnt(String pathName) {
zipFile = new File(pathName);
}

public void compress(String srcPathName) {
File srcdir = new File(srcPathName);
if (!srcdir.exists())
throw new RuntimeException(srcPathName + "不存在!");

Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
//fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
//fileSet.setExcludes(...); 排除哪些文件或文件夹
zip.addFileset(fileSet);

zip.execute();
}
}
测试一下
package net.szh.zip;

public class TestZip {
public static void main(String[] args) {
ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip");
zc.compress("E:\\test");

ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");
zca.compress("E:\\test");
}
}

10. java如何读取压缩包中的文本文件

压缩包的里的文件不能直接读取,只能先解压缩,再读取。
建议:可以用apache的工具类,先解压缩成临时文件,再读取,最后删除临时文件。

阅读全文

与java文本压缩相关的资料

热点内容
联想小新电脑怎么解压文件在哪里 浏览:225
while语句java 浏览:358
银行加密货币储蓄 浏览:461
map默认参数python 浏览:423
山西性能优良压缩机 浏览:197
欧洲tcc编程式模式公司 浏览:984
app的股权与投资怎么写 浏览:580
php网站首页文件 浏览:585
工商银行app怎么支持两个手机登录 浏览:106
安卓手机如何搭建ssr服务器 浏览:668
文件解压到一半跳出来需要密码 浏览:892
phpmysql编译pdo 浏览:514
怎么查看公司邮箱服务器地址 浏览:571
php可忽略大小写的模式符 浏览:947
白熊app稿费怎么样 浏览:464
新建的命令为 浏览:426
数组两种查找算法集合 浏览:757
dw怎么将源码拆成几个文件 浏览:231
验算法复核法 浏览:997
电脑管机就删除文件夹 浏览:482