在Java中替换所有文件类型中的字符串
我想在所有文件类型(尤其是二进制文件)中将字符串A替换为字符串B。我试过这个:在Java中替换所有文件类型中的字符串,java,file,binary,str-replace,Java,File,Binary,Str Replace,我想在所有文件类型(尤其是二进制文件)中将字符串A替换为字符串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)
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];
}
byte[]fileContent=Files.readAllBytes(file.toPath());
char[]charBuffer=新字符[fileContent.length];
对于(int i=0;i这样的东西应该可以工作:
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);
当然,它假设您在创建字符集对象之前知道正确的编码。只适用于小文件,大文件会很快填满您的堆。