我正在读取存储在zip文件中的XML文件。我需要删除空格,但似乎没什么用。这就是我所拥有的,但trim()没有做任何事情。
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
InputStream inputStream = zip.getInputStream(entry);
InputStreamReader inputStreamReader = InputStreamReader(inputStream);
char[] buffer = new char[1024];
while (inputStreamReader.read(buffer, 0, buffer.length) != -1) {
String str = new String(buffer);
System.out.println(str.trim());
}
答案 0 :(得分:2)
trim()将删除任何前导或尾随空格,但我认为您不能将trim命令与System.out.println结合使用。是否会捕获trim命令的结果?
您是否尝试过以下操作?
String result = str.trim();
System.out.println(result);
如果这不起作用,那么使用replaceAll()?
String result = str.replaceAll(" ","");
System.out.println(result);
或者,如果它不是一个简单的空白字符,尝试这样的东西,删除多个空格?
String result = str.replaceAll("\\s+","");
System.out.println(result);
答案 1 :(得分:1)
这可以解决您的问题。 打开拉链 - >阅读文件 - >修剪文件。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author comrench
*/
public class XMLTrim {
ZipEntry zipEntry;
Enumeration enumEntries;
BufferedReader bufferedReader;
InputStreamReader inputStreamReader;
ZipFile zip;
private String line=null;
public static void main(String[] args){
XMLTrim xmlTrim= new XMLTrim();
xmlTrim.trim();
}
public void trim(){
try {
Path tempPath=Paths.get("D:\\share\\tmp.zip");
zip = new ZipFile(tempPath.toFile());
Enumeration enumEntries= zip.entries();
while(enumEntries.hasMoreElements()){
zipEntry = (ZipEntry) enumEntries.nextElement();
readFileContent();
}
} catch (IOException ex) {
System.out.println("exception ex"+ex);
}
}
private void readFileContent() {
try {
inputStreamReader = new InputStreamReader(zip.getInputStream(zipEntry));
bufferedReader=new BufferedReader(inputStreamReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line.trim());
}
} catch (IOException e) {
System.out.println("Exception "+e);
}
}
}