java tostring apache,Java的Apache的文件实用readFileToString和writeStringToFile问题

I need to parse a java file (actually a .pdf) to an String and go back to a file. Between those process I'll apply some patches to the given string, but this is not important in this case.

I've developed the following JUnit test case:

String f1String=FileUtils.readFileToString(f1);

File temp=File.createTempFile("deleteme", "deleteme");

FileUtils.writeStringToFile(temp, f1String);

assertTrue(FileUtils.contentEquals(f1, temp));

This test converts a file to a string and writtes it back. However the test is failing.

I think it may be because of the encodings, but in FileUtils there is no much detailed info about this.

Anyone can help?

Thanks!

Added for further undestanding:

Why I need this?

I have very large pdfs in one machine, that are replicated in another one. The first one is in charge of creating those pdfs. Due to the low connectivity of the second machine and the big size of pdfs, I don't want to synch the whole pdfs, but only the changes done.

To create patches/apply them, I'm using the google library DiffMatchPatch. This library creates patches between two string. So I need to load a pdf to an string, apply a generated patch, and put it back to a file.

解决方案

Ed Staub awnser points why my solution is not working and he suggested using bytes instead of Strings. In my case I need an String, so the final working solution I've found is the following:

@Test

public void testFileRWAsArray() throws IOException{

String f1String="";

byte[] bytes=FileUtils.readFileToByteArray(f1);

for(byte b:bytes){

f1String=f1String+((char)b);

}

File temp=File.createTempFile("deleteme", "deleteme");

byte[] newBytes=new byte[f1String.length()];

for(int i=0; i

char c=f1String.charAt(i);

newBytes[i]= (byte)c;

}

FileUtils.writeByteArrayToFile(temp, newBytes);

assertTrue(FileUtils.contentEquals(f1, temp));

}

By using a cast between byte-char, I have the symmetry on conversion.

Thank you all!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值