نوشته شده توسط
ali zi zeperto
سلام
من یه فایل دارم که می خوام کل محتویاتش رو یکجا در یه رشته توی حافظه داشته باشم که باهاش کار کنم.البته رشته تغییر نمی کنه.می خوام بررسیش کنم.اندازه فایل هم به مگابایت نمی رسه.چطوری میشه اینکار رو کرد؟
قبلا این سوال مطرح شده توی اینترنت هم 1000 تا لینک در موردش هست.
public class MyUtil {
public byte[] readFileInBytes(File file) throws IOException {
if (file == null) throw new FileNotFoundException();
byte[] fileByte = new byte[(int)file.length()];
int myRead =0;
int counterByte =0;
/**
* Open the file
*/
FileInputStream fileInput = new FileInputStream(file);
/**
* filling the fileByte array with file's bytes
* -1 means end of file
*/
while((myRead = fileInput.read()) != -1) {
fileByte[counterByte ++] =(byte) myRead;
}
/**
* Close the file
*/
fileInput.close();
return fileByte;
}
}
این هم تستش که مطمئن باشی که کار می کنه
public class MyUtilTest {
private MyUtil myUtil;
@Before
public void setUp() {
this.myUtil = new MyUtil();
}
/**
* I pass a file which its size is 105,542 bytes
* This test method has to return me the above number
*/
@Test
public void testReadFileInBytes() throws Exception {
byte[] bytes = this.myUtil.readFileInBytes(new File("C:\\Winter.jpg"));
Assert.assertEquals(105542,bytes.length);
}
}