public static void writeFile(String strUrl, String fileName) {
URL url = null
try {
url = new URL(strUrl)
} catch (MalformedURLException e2) {
e2.printStackTrace()
}
InputStream is = null
try {
is = url.openStream()
} catch (IOException e1) {
e1.printStackTrace()
}
OutputStream os = null
try {
os = new FileOutputStream( fileName)
int bytesRead = 0
byte[] buffer = new byte[8192]
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead)
}
System.out.println("下载成功:"+strUrl)
} catch (FileNotFoundException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
}
import java.io.Fileimport java.io.FileNotFoundException
import java.io.IOException
import java.io.RandomAccessFile
public class Io{
public static void main(String [] s){
File filename = new File("F:\\suncity.txt")
String filein="你好!"
RandomAccessFile mm = null
try {
mm = new RandomAccessFile(filename,"rw")
mm.writeBytes(filein)
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace()
} finally{
if(mm!=null){
try {
mm.close()
} catch (IOException e2) {
// TODO 自动生成 catch 块
e2.printStackTrace()
}
}
}
}
}
在jsp/servlet中断点/多线程下载文件
<%@ page import="java.io.File" %><%@ page import="java.io.IOException" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.io.RandomAccessFile" %>
<%!
public void downloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
RandomAccessFile raf = new RandomAccessFile(file, "r")
java.io.FileInputStream fis = new java.io.FileInputStream(raf.getFD())
response.setHeader("Server", "www.trydone.com")
response.setHeader("Accept-Ranges", "bytes")
long pos = 0
long len
len = raf.length()
if (request.getHeader("Range") != null) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT)
pos = Long.parseLong(request.getHeader("Range")
.replaceAll("bytes=", "")
.replaceAll("-", "")
)
}
response.setHeader("Content-Length", Long.toString(len - pos))
if (pos != 0) {
response.setHeader("Content-Range", new StringBuffer()
.append("bytes ")
.append(pos)
.append("-")
.append(Long.toString(len - 1))
.append("/")
.append(len)
.toString()
)
}
response.setContentType("application/octet-stream")
response.setHeader("Content-Disposition", new StringBuffer()
.append("attachmentfilename=\"")
.append(file.getName())
.append("\"").toString())
raf.seek(pos)
byte[] b = new byte[2048]
int i
OutputStream outs = response.getOutputStream()
while ((i = raf.read(b)) != -1) {
outs.write(b, 0, i)
}
raf.close()
fis.close()
}
%>
<%
String filePath = request.getParameter("file")
filePath = application.getRealPath(filePath)
File file = new File(filePath)
downloadFile(request, response, file)
%>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)