「java算法实现数据压缩」java 字符串压缩与解压算法

博主:adminadmin 2022-11-24 21:00:10 71

本篇文章给大家谈谈java算法实现数据压缩,以及java 字符串压缩与解压算法对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

用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();

}

}

JAVA 压缩和序列化

压缩和序列化主要用在数据的存储和传输上,二者都是由IO流相关知识实现,这里统一介绍下。

全部章节传送门:

Java I/O类支持读写压缩格式的数据流,你可以用他们对其他的I/O流进行封装,以提供压缩功能。

GZIP接口比较简单,适合对单个数据流进行压缩,在Linux系统中使用较多。

ZIP格式可以压缩多个文件,而且可以和压缩工具进行协作,是经常使用的压缩方法。

JAR(Java Archive,Java 归档文件)是与平台无关的文件格式,它允许将许多文件组合成一个压缩文件。为 J2EE 应用程序创建的 JAR 文件是 EAR 文件(企业 JAR 文件)。

JAR 文件格式以流行的 ZIP 文件格式为基础。与 ZIP 文件不同的是,JAR 文件不仅用于压缩和发布,而且还用于部署和封装库、组件和插件程序,并可被像编译器和 JVM 这样的工具直接使用。在 JAR 中包含特殊的文件,如 manifests 和部署描述符,用来指示工具如何处理特定的 JAR。

如果一个Web应用程序的目录和文件非常多,那么将这个Web应用程序部署到另一台机器上,就不是很方便了,我们可以将Web应用程序打包成Web 归档(WAR)文件,这个过程和把Java类文件打包成JAR文件的过程类似。利用WAR文件,可以把Servlet类文件和相关的资源集中在一起进行发布。在这个过程中,Web应用程序就不是按照目录层次结构来进行部署了,而是把WAR文件作为部署单元来使用。

一个WAR文件就是一个Web应用程序,建立WAR文件,就是把整个Web应用程序(不包括Web应用程序层次结构的根目录)压缩起来,指定一个.war扩展名。下面我们将第2章的Web应用程序打包成WAR文件,然后发布

要注意的是,虽然WAR文件和JAR文件的文件格式是一样的,并且都是使用jar命令来创建,但就其应用来说,WAR文件和JAR文件是有根本区别的。JAR文件的目的是把类和相关的资源封装到压缩的归档文件中,而对于WAR文件来说,一个WAR文件代表了一个Web应用程序,它可以包含 Servlet、HTML页面、Java类、图像文件,以及组成Web应用程序的其他资源,而不仅仅是类的归档文件。

在命令行输入jar即可查看jar命令的使用方法。

把对象转换为字节序列的过程称为对象的序列化。把字节序列恢复为对象的过程称为对象的反序列化。

对象的序列化主要有两种用途:

java.io.ObjectOutputStream代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。

java.io.ObjectInputStream代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回。

只有实现了Serializable的对象才能被序列化。对象序列化包括如下步骤:

对象反序列化的步骤如下:

创建一个可以可以序列化的对象。

然后进行序列化和反序列化测试。

serialVersionUID: 字面意思上是序列化的版本号,凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量。

JAVA序列化的机制是通过判断类的serialVersionUID来验证的版本一致的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID于本地相应实体类的serialVersionUID进行比较。如果相同说明是一致的,可以进行反序列化,否则会出现反序列化版本一致的异常,即是InvalidCastException。

为了提高serialVersionUID的独立性和确定性,强烈建议在一个可序列化类中显示的定义serialVersionUID,为它赋予明确的值。

控制序列化字段还可以使用Externalizable接口替代Serializable借口。此时需要定义一个默认构造器,否则将为得到一个异常(java.io.InvalidClassException: Person; Person; no valid constructor);还需要定义两个方法(writeExternal()和readExternal())来控制要序列化的字段。

如下为将Person类修改为使用Externalizable接口。

transient修饰符仅适用于变量,不适用于方法和类。在序列化时,如果我们不想序列化特定变量以满足安全约束,那么我们应该将该变量声明为transient。执行序列化时,JVM会忽略transient变量的原始值并将默认值(引用类型就是null,数字就是0)保存到文件中。因此,transient意味着不要序列化。

静态变量不是对象状态的一部分,因此它不参与序列化。所以将静态变量声明为transient变量是没有用处的。

java编程:数据压缩规则

你是不是问如何编写一个程序来压缩数据?如果你是想解决这个问题的话,继续往下看,如果你只是想要应付考试的话就算了。

—— 分割线

JDK本身提供了数据压缩的一个API

java.util.zip.Deflater.deflateBytes(byte[] b, int off, int len)

以下是我使用的一个例子,有点多,注释看不懂可以问我,不知道怎么用可以问我,其他的就算了。

/**

* threshold value for compress

*/

public static final int THRESHOLD = 1200;

/**

* Answer a byte array compressed in the DEFLATER format from bytes.

*

* @param bytes

* a byte array

* @return byte[] compressed bytes

* @throws IOException

*/

public static byte[] compress(byte[] bytes)

{

// Create the compressor with highest level of compression

Deflater compressor = new Deflater();

compressor.setLevel(Deflater.BEST_COMPRESSION);

// Give the compressor the data to compress

compressor.setInput(bytes);

compressor.finish();

// Create an expandable byte array to hold the compressed data.

// You cannot use an array that's the same size as the orginal because

// there is no guarantee that the compressed data will be smaller than

// the uncompressed data.

ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);

// Compress the data

byte[] buf = new byte[1024];

while (!compressor.finished())

{

int count = compressor.deflate(buf);

bos.write(buf, 0, count);

}

try

{

bos.close();

}

catch (IOException e)

{

}

// Get the compressed data

byte[] compressedData = bos.toByteArray();

return compressedData;

}

/**

* Answer a byte array that has been decompressed from the DEFLATER format.

*

* @param bytes

* a byte array

* @return byte[] compressed bytes

* @throws IOException

*/

public static byte[] uncompress(byte[] bytes)

{

// Create the decompressor and give it the data to compress

Inflater decompressor = new Inflater();

decompressor.setInput(bytes);

// Create an expandable byte array to hold the decompressed data

ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);

// Decompress the data

byte[] buf = new byte[1024];

while (!decompressor.finished())

{

try

{

int count = decompressor.inflate(buf);

bos.write(buf, 0, count);

}

catch (DataFormatException e)

{

}

}

try

{

bos.close();

}

catch (IOException e)

{

}

// Get the decompressed data

byte[] decompressedData = bos.toByteArray();

return decompressedData;

}

如何使用JAVA代码压缩PDF文件

用java代码压缩应用到程序了,代码一般是比较复杂的,对pdf文件的mate标签优化,这类标签包括三类,pdf文件不是网页就是个文件,何况我们可以用pdf压缩工具压缩,下面有个解决方法,楼主可以做参照。

1:点击打开工具,打开主页面上有三个功能进行选择,我们选择pdf文件压缩。

2:这这个页面中我们选择pdf文件在这里打开,点击“添加文件”按钮将文件添加进来。

3:然后在页面中点击“开始压缩”就可以开始压缩文件了。

4:压缩完成的文件页面会显示已经完成。

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

package zip;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.Enumeration;

import java.util.zip.CRC32;

import java.util.zip.CheckedOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;

import org.apache.commons.lang3.StringUtils;

public class ZipUtil {

/**

 * 递归压缩文件夹

 * @param srcRootDir 压缩文件夹根目录的子路径

 * @param file 当前递归压缩的文件或目录对象

 * @param zos 压缩文件存储对象

 * @throws Exception

 */

private static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception

{

if (file == null) 

{

return;

}

//如果是文件,则直接压缩该文件

if (file.isFile())

{

int count, bufferLen = 1024;

byte data[] = new byte[bufferLen];

//获取文件相对于压缩文件夹根目录的子路径

String subPath = file.getAbsolutePath();

int index = subPath.indexOf(srcRootDir);

if (index != -1) 

{

subPath = subPath.substring(srcRootDir.length() + File.separator.length());

}

ZipEntry entry = new ZipEntry(subPath);

zos.putNextEntry(entry);

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

while ((count = bis.read(data, 0, bufferLen)) != -1) 

{

zos.write(data, 0, count);

}

bis.close();

zos.closeEntry();

}

//如果是目录,则压缩整个目录

else 

{

//压缩目录中的文件或子目录

File[] childFileList = file.listFiles();

for (int n=0; nchildFileList.length; n++)

{

childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());

zip(srcRootDir, childFileList[n], zos);

}

}

}

/**

 * 对文件或文件目录进行压缩

 * @param srcPath 要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径

 * @param zipPath 压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹

 * @param zipFileName 压缩文件名

 * @throws Exception

 */

public static void zip(String srcPath, String zipPath, String zipFileName) throws Exception

{

if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(zipPath) || StringUtils.isEmpty(zipFileName))

{

throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);

}

CheckedOutputStream cos = null;

ZipOutputStream zos = null;

try

{

File srcFile = new File(srcPath);

//判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)

if (srcFile.isDirectory()  zipPath.indexOf(srcPath)!=-1) 

{

throw new ParameterException(ICommonResultCode.INVALID_PARAMETER, "zipPath must not be the child directory of srcPath.");

}

//判断压缩文件保存的路径是否存在,如果不存在,则创建目录

File zipDir = new File(zipPath);

if (!zipDir.exists() || !zipDir.isDirectory())

{

zipDir.mkdirs();

}

//创建压缩文件保存的文件对象

String zipFilePath = zipPath + File.separator + zipFileName;

File zipFile = new File(zipFilePath);

if (zipFile.exists())

{

//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException

SecurityManager securityManager = new SecurityManager();

securityManager.checkDelete(zipFilePath);

//删除已存在的目标文件

zipFile.delete();

}

cos = new CheckedOutputStream(new FileOutputStream(zipFile), new CRC32());

zos = new ZipOutputStream(cos);

//如果只是压缩一个文件,则需要截取该文件的父目录

String srcRootDir = srcPath;

if (srcFile.isFile())

{

int index = srcPath.lastIndexOf(File.separator);

if (index != -1)

{

srcRootDir = srcPath.substring(0, index);

}

}

//调用递归压缩方法进行目录或文件压缩

zip(srcRootDir, srcFile, zos);

zos.flush();

}

catch (Exception e) 

{

throw e;

}

finally 

{

try

{

if (zos != null)

{

zos.close();

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

/**

 * 解压缩zip包

 * @param zipFilePath zip文件的全路径

 * @param unzipFilePath 解压后的文件保存的路径

 * @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含

 */

@SuppressWarnings("unchecked")

public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception

{

if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(unzipFilePath))

{

throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);

}

File zipFile = new File(zipFilePath);

//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径

if (includeZipFileName)

{

String fileName = zipFile.getName();

if (StringUtils.isNotEmpty(fileName))

{

fileName = fileName.substring(0, fileName.lastIndexOf("."));

}

unzipFilePath = unzipFilePath + File.separator + fileName;

}

//创建解压缩文件保存的路径

File unzipFileDir = new File(unzipFilePath);

if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())

{

unzipFileDir.mkdirs();

}

//开始解压

ZipEntry entry = null;

String entryFilePath = null, entryDirPath = null;

File entryFile = null, entryDir = null;

int index = 0, count = 0, bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

ZipFile zip = new ZipFile(zipFile);

EnumerationZipEntry entries = (EnumerationZipEntry)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 = new File(entryDirPath);

//如果文件夹路径不存在,则创建文件夹

if (!entryDir.exists() || !entryDir.isDirectory())

{

entryDir.mkdirs();

}

//创建解压文件

entryFile = new File(entryFilePath);

if (entryFile.exists())

{

//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException

SecurityManager securityManager = new SecurityManager();

securityManager.checkDelete(entryFilePath);

//删除已存在的目标文件

entryFile.delete();

}

//写入文件

bos = new BufferedOutputStream(new FileOutputStream(entryFile));

bis = new BufferedInputStream(zip.getInputStream(entry));

while ((count = bis.read(buffer, 0, bufferSize)) != -1)

{

bos.write(buffer, 0, count);

}

bos.flush();

bos.close();

}

}

public static void main(String[] args) 

{

String zipPath = "d:\\ziptest\\zipPath";

String dir = "d:\\ziptest\\rawfiles";

String zipFileName = "test.zip";

try

{

zip(dir, zipPath, zipFileName);

catch (Exception e)

{

e.printStackTrace();

}

String zipFilePath = "D:\\ziptest\\zipPath\\test.zip";

String unzipFilePath = "D:\\ziptest\\zipPath";

try 

{

unzip(zipFilePath, unzipFilePath, true);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

java算法实现数据压缩的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java 字符串压缩与解压算法、java算法实现数据压缩的信息别忘了在本站进行查找喔。

The End

发布于:2022-11-24,除非注明,否则均为首码项目网原创文章,转载请注明出处。