日期:2014-05-20  浏览次数:20905 次

高分求救:RandomAccessFile读取文件的问题
需求:servlet中下载文件,如果下载的文件很大,需要用 RandomAccessFile类,
   要求传入三个参数:文件名,读文件的起始位置(比如第一次从0字节,第二次从64+1字节开始读),一次读的字节数(64K);
哪位高手帮写一下,实在不懂,很急!!


------解决方案--------------------
seek(start);
read(byte[] b, int off, int len) ;
------解决方案--------------------
/**
* copy file from url
* @param sourceURL source file 's url
* @param destFilePath direct file name
* @return boolean
*/
public static boolean copyFromURL(String sourceURL, String destFilePath) {
System.out.println( "sourceURL = " + sourceURL);
RandomAccessFile destFile = null;
InputStream inStream = null;
try {
destFile = new RandomAccessFile(destFilePath, "rw ");
URL url = new java.net.URL(sourceURL);
URLConnection conn = url.openConnection();
inStream = conn.getInputStream();
byte[] buffer = new byte[512];

int lineRead = 0;
while ( (lineRead = inStream.read(buffer, 0, 512)) != -1) { //EOF
destFile.write(buffer, 0, lineRead);
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
try {
if (destFile != null) {
destFile.close();
}
}
catch (Exception e) {
}

try {
if (inStream != null) {
inStream.close();
}
}
catch (Exception e) {
}
}
return true;
}
------解决方案--------------------
public byte[] randomRead(String pm_sFilePath,int pm_iBeginIndex,int pm_iLenth)
{
try
{
RandomAccessFile file = new RandomAccessFile( "./keyCode.data ", "rw ");
int iFileLength = (int)file.length();
if(pm_iBeginIndex <0)
{
System.out.println( "can 't begin with "+pm_iBeginIndex);
return null;
}
else if(pm_iBeginIndex+pm_iLenth> iFileLength)
{
System.out.println( "length exceeded! ");
return null;
}
else
{
byte[] ret = new byte[pm)iLenth];
file.seek(pm_iBeginIndex);
file.read(ret,pm_iBeginIndex,pm_iLenth);
return ret;
}
}
catch(IOException es)
{
es.printStackTrace();
return null;
}
}