자바 다 중 스 레 드 정지점 전송(HTTP 기반)
package com.itheima.net.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* (HTTP)
* @author Bin
* Windows NT 6.1
*/
public class TextThreadsAndPointAdd {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String webAddr="http://nchc.dl.sourceforge.net/project/jtidy/JTidy/r938/jtidy-r938.zip";
String fileDir="F:/temp";
String fileName="ss.zip";
int count=5;
new TextThreadsAndPointAdd(webAddr,fileDir,fileName,count);
}
public TextThreadsAndPointAdd(String webAddr,String fileDir,String fileName,int count) {
try {
TranBean bean=new TranBean(webAddr,fileDir,fileName,count);
ControlFileFetch fileFetch=new ControlFileFetch(bean);
fileFetch.start();
} catch (Exception e) {
System.out.println(" :"+e.getMessage());
System.exit(1);
}
}
}
// , ,
class ControlFileFetch extends Thread{
TranBean tranBean=null; // bean
long [] startPosition; //
long [] endPosition; //
FileFetch[] childThread; //
long fileLength; //
boolean isFitstGet=true; //
boolean isStopGet=false; //
File fileName; //
DataOutputStream output; //
public ControlFileFetch(TranBean tranBean){
this.tranBean=tranBean;
fileName=new File(tranBean.getFileDir()+File.separator+tranBean.getFileName()+".info"); //
System.out.println(tranBean.getFileDir()+File.separator+tranBean.getFileName()+".info");
if(fileName.exists()){
isFitstGet=false;
readInfo();
}else{
startPosition=new long[tranBean.getCount()];
endPosition =new long[tranBean.getCount()];
}
}
public void run(){
try {
if(isFitstGet){ //
fileLength=getFieldSize(); //
if(fileLength==-1){
System.err.println(" ");
}else if(fileLength==-2){
System.err.println(" ");
}else{
System.out.println(" :"+fileLength);
//
for (int i = 0; i < startPosition.length; i++) {
startPosition[i]=(long)(i*(fileLength/startPosition.length));
}
//
for (int i = 0; i < endPosition.length-1; i++) {
endPosition[i]=startPosition[i+1];
}
//
endPosition[endPosition.length-1]=fileLength;
}
}
//
childThread=new FileFetch[startPosition.length];
for (int i = 0; i < startPosition.length; i++) {
childThread[i]=new FileFetch(tranBean.getWebAddr(), tranBean.getFileDir()+File.separator+tranBean.getFileName(), startPosition[i], endPosition[i], i);
Log.log(" "+(i+1)+", ="+startPosition[i]+", ="+endPosition[i]);
childThread[i].start();
}
boolean breakWhile=false;
while (!isStopGet) {
savePosition();
Log.sleep(500);//
breakWhile=true;
for (int i = 0; i < startPosition.length; i++) { //
if(!childThread[i].downLoadOver){
breakWhile=false;
break;
}
}
if(breakWhile)
break;
}
System.err.println(" !");
} catch (Exception e) {
System.out.println(" :"+e.getMessage());
}
}
// ( )
private void savePosition() {
try {
output=new DataOutputStream(new FileOutputStream(fileName));
output.writeInt(startPosition.length);
for (int i = 0; i < startPosition.length; i++) {
output.writeLong(childThread[i].startPosition);
output.writeLong(childThread[i].endPosition);
}
output.close();
} catch (Exception e) {
System.out.println(" :"+e.getMessage());
}
}
//
public long getFieldSize(){
int fileLength=-1;
try {
URL url=new URL(tranBean.getWebAddr()); // URL
//
HttpURLConnection httpConnection=(HttpURLConnection)url.openConnection();
// HTTP
httpConnection.setRequestProperty("User-Agent", "NetFox");
int responseCode=httpConnection.getResponseCode();
//
if(responseCode>=400){
errorCode(responseCode);
return -2;
}
String head;
for (int i = 1; ; i++) {
head=httpConnection.getHeaderFieldKey(i); //
if(head !=null){
if(head.equals("Content-Length")){ //
fileLength=Integer.parseInt(httpConnection.getHeaderField(head));
break;
}
}else{
break;
}
}
} catch (Exception e) {
System.out.println(" :"+e.getMessage());
}
Log.log(" "+fileLength);
return fileLength;
}
private void errorCode(int errorCode){
System.out.println(" :"+errorCode);
}
//
private void readInfo(){
try {
//
DataInputStream input=new DataInputStream(new FileInputStream(fileName));
int count=input.readInt(); //
startPosition=new long[count]; //
endPosition=new long[count]; //
for (int i = 0; i < startPosition.length; i++) {
startPosition[i]=input.readLong(); //
endPosition[i]=input.readLong(); //
}
input.close();
} catch (Exception e) {
System.out.println(" :"+e.getMessage());
}
}
}
// ,
class FileFetch extends Thread{
String webAddr; //
long startPosition; //
long endPosition; //
int threadID; //
boolean downLoadOver=false; //
boolean isStopGet=false; //
FileAccess fileAccessI=null; //
public FileFetch(String surl,String sname, long startPosition, long endPosition,
int threadID) throws IOException {
this.webAddr = surl;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.threadID = threadID;
this.fileAccessI = new FileAccess(sname,startPosition);
}
//
public void run(){
while (startPosition < endPosition && !isStopGet) {
try {
URL url=new URL(webAddr); // URL
HttpURLConnection httpConnection=(HttpURLConnection)url.openConnection(); //
// HTTP
httpConnection.setRequestProperty("User-Agent", "NetFox");
String sproperty="byte="+startPosition+"-";
httpConnection.setRequestProperty("RANGE", sproperty);
Log.log(sproperty);
//
InputStream input=httpConnection.getInputStream();
byte[] b=new byte[1024];
int nRead;
//
while ((nRead=input.read(b, 0, 1024))>0 && startPosition < endPosition && !isStopGet) {
startPosition+=fileAccessI.write(b, 0, nRead); //
}
Log.log(" \t"+(threadID+1)+"\t ....");
downLoadOver=true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
//
public void logResponseHead(HttpURLConnection con){
for (int i = 1; ; i++) {
String header=con.getHeaderFieldKey(i); //
if(header!=null){
Log.log(header+":"+con.getHeaderField(header));
}else
break;
}
}
public void splitterStop(){
isStopGet=true;
}
}
//
class FileAccess implements Serializable{
RandomAccessFile saveFile; //
long position;
public FileAccess() throws IOException {
this("",0);
}
public FileAccess(String sname, long position) throws IOException {
this.saveFile =new RandomAccessFile(sname, "rw"); // , /
this.position = position;
saveFile.seek(position); //
}
//
public synchronized int write(byte[] b,int start,int length){
int n=-1;
try {
saveFile.write(b,start,length);
n=length;
} catch (Exception e) {
e.printStackTrace();
}
return n;
}
}
//
class TranBean {
private String webAddr; //
private String fileDir; //
private String fileName; //
private int count; // , 3
public TranBean() { //
this("","","",3);
} //
public TranBean(String webAddr, String fileDir, String fileName, int count) {
this.webAddr = webAddr;
this.fileDir = fileDir;
this.fileName = fileName;
this.count = count;
}
public String getWebAddr() {
return webAddr;
}
public void setWebAddr(String webAddr) {
this.webAddr = webAddr;
}
public String getFileDir() {
return fileDir;
}
public void setFileDir(String fileDir) {
this.fileDir = fileDir;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
//
class Log{
public Log(){}
public static void sleep(int nsecond){
try {
Thread.sleep(nsecond);
} catch (Exception e) {
System.out.println(" ");
}
}
public static void log(String message){ //
System.err.println(message);
}
public static void log(int message){ //
System.err.println(message);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.