用Java替换所有文件类型中的字符串

时间:2015-05-12 15:36:00

标签: java file binary str-replace

我想在所有文件类型中将String A替换为String B,尤其是二进制文件。我试过这个:

byte[] fileContent= Files.readAllBytes(file.toPath());
String content= new String(fileContent,charset);
content=content.replace(A,B);
byte[] result= content.getBytes(charset);
Files.write(file.toPath(), result);

但它不适用于JPG等二进制文件。使用txt文件效果很好。

然后我写了这个:

            byte[] fileContent= Files.readAllBytes(file.toPath());

            char[] charBuffer=new char[fileContent.length];

            for(int i=0;i<fileContent.length;i++)
            {
                charBuffer[i]=(char)fileContent[i];
            }

            String content=new String(charBuffer);
            content=content.replace(chainA, chainB);

            charBuffer=content.toCharArray();
            fileContent=new byte[charBuffer.length];

            for(int i=0;i<charBuffer.length;i++)
            {
                fileContent[i]=(byte)charBuffer[i];
            }

它很棒。我的问题是:有没有更好的方法来替换二进制和txt文件中的两个字符串?

为什么我的第一个代码不适用于二进制文件?

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

Charset isoCharset = Charset.forName ("ISO-8859-1");
byte[] fileContent = Files.readAllBytes (file.toPath ());
String.content = new String (fileContent, isoCharset);
content = content.replace (chainA, chainB);
fileContent = content.getBytes (isoCharset);

当然,它假定您在创建Charset对象之前知道正确的编码。