我正在生成这样的文本段落:
>1. this is the first line
>1. this is the second line
>1. this is the third line
>1. this is the fourth line
然后将其存储在一个字符串中
然后我想将此字符串输出到压缩文本文档,一切正常,但是当我打开使用 FileOutputStream 创建的文本文件时格式不存在,你知道我如何检索格式吗?
代码:
try
{
String toZip = file.toString();
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("test.zip")));
ZipOutputStream zos = new ZipOutputStream(dos);
byte[] b = toZip.getBytes("UTF8");
ZipEntry entry = new ZipEntry("TheFirstFile.txt");
System.out.println("Zipping.." + entry.getName());
zos.putNextEntry(entry);
zos.write(b, 0, b.length);
dos.close();
zos.close();
}
catch (IOException e)
{
e.printStackTrace();
} catch (MyException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
在这里发布代码时遇到问题.. 测试程序:
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class TestZip {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\TEMP\\tests.txt"),"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = br.readLine();
try
{
while(line != null)
{
if(line != null)
{
buffer.append(line + "\n");
}
line=br.readLine();
}
String data = buffer.toString();
br.close();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:\\TEMP\\ZippedFile.zip"));
ZipOutputStream zos = new ZipOutputStream(bos);
System.out.println(data);
byte[] b = data.getBytes();
ZipEntry entry = new ZipEntry("TheData.txt");
System.out.println("Zipping.." + entry.getName());
zos.putNextEntry(entry);
zos.write(b, 0, b.length);
zos.closeEntry();
zos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
当我在控制台上打印出来时,文本的边距是我想要的,当我检查压缩文本文件时,文本都在一行上。
控制台输出:
文本文件结果:
我希望它在文本文件中完全显示在控制台中的打印方式。
我以前从未编写过可以读取压缩文本文件的程序,但我尝试过..
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class TestUnzip {
public static void main (String[] args) {
String unzip = "";
try
{
FileInputStream fin = new FileInputStream("C:\\TEMP\\ZippedFile.zip");
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze;
byte[] bytes = new byte[1024];
ze = zin.getNextEntry();
while ((ze = zin.getNextEntry()) != null)
{
if (zin.read(bytes, 0, bytes.length) != -1)
{
unzip = new String(bytes, "UTF-8");
}
else
{
System.out.println("error");
}
ze = zin.getNextEntry();
}
System.out.println(unzip.toString());
zin.closeEntry();
zin.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}