Java项目实训
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java项目实训
一、将服务器上的资源读到本机
1、从键盘输入网址,将该网址的内容读入到本机并输出 import
.*;
import java.io.*;
import java.util.*; public class Lx1 {
public static void main(String args[]) {
Scanner scanner;
URL url;
"输入URL资源,例如:");
scanner = new Scanner(System.in); String source =
scanner.nextLine(); try {
url = new URL(source);
InputStream in = url.openStream(); byte [] b = new
byte[1024]; int n=-1;
while((n=in.read(b))!=-1) {
String str = new String(b,0,n);
}
}
catch(Exception exp){
}
}
2、从键盘输入网址,将该网址的内容读入到本机并输出到一个文件 import
urltext 中。.*;
import java.io.*;
import java.io.*;
import java.util.*;
public class Lx2 {
public static void main(String args[]) {
Scanner scanner;
URL url;
"输入URL资源,例如:”);
scanner = new Scanner(System.in);
String source = scanner.nextLine();
try {
url = new URL(source);
InputStream in = url.openStream(); byte [] b = new
byte[1024];
int n=-1;
FileOutputStream out=new
FileOutputStream("urltext.txt");
while((n=in.read(b))!=-1) {
String str = new String(b,0,n);
out.write(b,0,n);
}
}
catch(Exception exp){
}
}
3、用线程技术实现上述程序
import .*;
import java.io.*;
import java.util.*;
public class Example13_1 {
public static void main(String args[]) {
Scanner scanner;
URL url;
Thread readURL;
Look look = new Look();
"输入URL资源,例如:”);
scanner = new Scanner(System.in); String source =
scanner.nextLine(); try { url = new URL(source);
look.setURL(url); readURL = new Thread(look);
}
catch(Exception exp){
}
readURL = new Thread(look); readURL.start();
}
}
import .*;
import java.io.*;
public class Look implements Runnable { URL url;
public void setURL(URL url) { this.url=url;
}
public void run() {
try {
InputStream in = url.openStream(); byte [] b = new byte[1024]; int n=-1;
while((n=in.read(b))!=-1) {
String str = new String(b,0,n);
}
} catch(IOException exp){}
}
}
二、读取主机地址和本机地址
1、调试下列读取主机名称及 IP 地址的程序 import .*;
public class Example13_2 {
public static void main(String args[]) {
try{ InetAddress address_1=InetAddress.getByName("");
InetAddress address_2=InetAddress.getByName("");
} catch(UnknownHostException e) {
" 无法找到 ");
}
}
}
2、从键盘输入任意主机名,读取主机地址、本机地址 import .*;
import java.io.*;
import java.io.*;
import java.util.*;
public class Ex2 {
public static void main(String args[]) {
Scanner scanner;
URL url;
"输入URL资源例如:”);
scanner = new Scanner(System.in);
String source = scanner.nextLine();
try{ InetAddress address_1=InetAddress.getByName(source);
InetAddress address_2=InetAddress.getLocalHost();