-应用一
需求:
客户端通过键盘输入用户名
服务端对这个用户名进行校验
然后该用户名存在,在服务端显示 XXX,登录成功
并在客户端显示:欢迎你,XXX
如果某不存在的用户 在登录,在服务端显示XXX,尝试登录
并在客户端显示: 用户XXX,不存在
最多可以尝试登录3次
-获取IP地址的小程序
-结合GUI编程编写的一个批量更改文件/文件夹名称的小应用(写这个小应用原因只要是由于一些视频文件老是带着很长的无用字符,比如传智播客的很多视频教程--囧囧--)
需求:
客户端通过键盘输入用户名
服务端对这个用户名进行校验
然后该用户名存在,在服务端显示 XXX,登录成功
并在客户端显示:欢迎你,XXX
如果某不存在的用户 在登录,在服务端显示XXX,尝试登录
并在客户端显示: 用户XXX,不存在
最多可以尝试登录3次
package day24;
import java.io.*;
import java.net.*;
/**
* 功能:
*
* 客户端通过键盘输入用户名
* 服务端对这个用户名进行校验
*
* 然后该用户名存在,在服务端显示 XXX,登录成功
* 并在客户端显示:欢迎你,XXX
*
* 如果某不存在的用户 在登录,在服务端显示XXX,尝试登录
* 并在客户端显示: 用户XXX,不存在
* 最多可以尝试登录3次
*
*/
//服务端程序
class UserThread implements Runnable{
private Socket s;
UserThread(Socket s){
this.s= s;
}
public void run(){
String ip= s.getInetAddress().getHostAddress();
System.out.println("来自:"+ip+" 的用户正在准备登录");
try {
for(int i=0;i<3;i++){
BufferedReader bufIn= new BufferedReader(new InputStreamReader(s.getInputStream()));
String name= bufIn.readLine();
//从相当于数据库中用户表出user.txt文件读取数据和客户端发过来的用户名数据进行比较
BufferedReader bufr= new BufferedReader(new FileReader("user.txt"));
PrintWriter out= new PrintWriter(s.getOutputStream(),true);
String line= null;
boolean flag= false;//定义一个标识符
while((line= bufr.readLine())!= null){
if(line.equals(name)){
flag= true;
break;
}
}
if(flag){
System.out.println(name+"-已登录");
out.println("欢迎您,"+name);
break;
}
else{
System.out.println(name+",正在尝试登录");
out.println(name+",用户名不存在");
}
}
s.close();
} catch (Exception e) {
throw new RuntimeException("校验失败");
}
}
}
class LoginServer{
public static void main(String[] args) throws Exception{
ServerSocket ss= new ServerSocket(11001);
while(true){
Socket s= ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
//客户端
class LoginClient {
public static void main(String[] args) throws Exception{
Socket s= new Socket("10.0.31.236",11000);
BufferedReader bufr= new BufferedReader(new InputStreamReader(System.in));
PrintWriter out= new PrintWriter(s.getOutputStream(),true);//老是忘记写 true!!!!!
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
for(int i=0; i<3;i++){
String line= bufr.readLine();
//判断键盘输入是否为空,否则发给服务端
if(line==null)
break;
out.println(line);
String info= bufIn.readLine();
System.out.println("info:"+info);
if(info.contains("欢迎"))
break;
}
bufr.close();
s.close();
}
}
</pre><p>-应用二:结合GUI编程实现一个带页面的简易浏览器</p><p></p><pre name="code" class="java">package day24;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class MyIEByGUI2 {
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okBut;
MyIEByGUI2(){
init();
}
public void init(){
f= new Frame("my IE window");
f.setBounds(300, 100, 600, 500);
f.setLayout(new FlowLayout());
tf= new TextField(60);
but= new Button("转到");
ta= new TextArea(25,70);
d= new Dialog(f,"提示信息-self",true);
d.setBounds(400, 200, 240, 150);
d.setLayout(new FlowLayout());
lab= new Label();
okBut= new Button("确定");
d.add(lab);
d.add(okBut);
f.add(tf);
f.add(but);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent() {
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
d.setVisible(false);
}
});
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
d.setVisible(false);
}
});
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
try {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
showDir();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
but.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
showDir();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
private void showDir() throws Exception{
ta.setText("");
String urlPath= tf.getText();//http://10.0.31.236:8080/testWeb/demo.html
//-------------MyIEByGUI2版本代码------------
URL url= new URL(urlPath);
URLConnection conn= url.openConnection();
InputStream in= conn.getInputStream();
byte[] buf= new byte[1024];
int len= in.read(buf);
ta.setText(new String(buf,0,len));
//-------------MyIEByGUI版本代码-------------
// int index1= url.indexOf("//")+2;
// int index2= url.indexOf("/",index1);
//
// String str= url.substring(index1, index2);
// String[] arr= str.split(":");
// String host= arr[0];
// int port= Integer.parseInt(arr[1]);
//
// String path= url.substring(index2);
// //ta.setText(str+"......"+path);
//
// Socket s= new Socket(host,port);
//
// PrintWriter out = new PrintWriter(s.getOutputStream(),true);
//
// out.println("GET "+path+" HTTP/1.1");
// out.println("Accept: */*");
// out.println("Accept-Language: zh-cn");
// out.println("Host:10.0.31.236:11004");
// out.println("Connetion:closed");
//
// out.println();
// out.println();
//
// BufferedReader bufr= new BufferedReader(new InputStreamReader(s.getInputStream()));
//
// String line=null;
// while((line=bufr.readLine())!= null){
// //System.out.println(line);
// ta.append(line+"\r\n");
// }
// s.close();
//-------------MyIE版本代码-------------
// String dirPath= tf.getText();
// File dir= new File(dirPath);
//
// if(dir.exists()&& dir.isDirectory()){
// ta.setText("");
// String[] names= dir.list();
// for(String name: names){
// ta.append(name+"\r\n");
// }
// }
// else{
// String info= "你输入的信息:"+dirPath+"出错,请重新输入";
// lab.setText(info);
// d.setVisible(true);
// }
}
public static void main(String[] args){
new MyIEByGUI2();
}
}
-获取IP地址的小程序
package day24;
import java.io.*;
import java.net.*;
public class GetIPDemo {
public static void main(String[] args){
BufferedReader bufr= null;
try {
bufr= new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入域名:");
String line=null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
InetAddress ip= Inet4Address.getByName(line);
System.out.println("IP地址为:"+ip);
}
} catch (Exception e) {
throw new RuntimeException("输入域名不正确,请重输");
}finally{
try {
bufr.close();
} catch (Exception e2) {
throw new RuntimeException("输入流关闭失败");
}
}
}
}
-结合GUI编程编写的一个批量更改文件/文件夹名称的小应用(写这个小应用原因只要是由于一些视频文件老是带着很长的无用字符,比如传智播客的很多视频教程--囧囧--)
package communal;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.JOptionPane;
//批量重命名文件或者目录的小工具类
public class RenameTool {
private Frame f;
private TextField tDir, tOldField, tNewField;
private Button b;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okB;
private Boolean bl = false;
public RenameTool() {
init();
}
private void init() {
f = new Frame("批量更改文件名工具");
f.setBounds(280, 80, 590, 650);
f.setLayout(new FlowLayout());
tDir = new TextField(26);
tDir.setText("请输入文件路径");
tOldField = new TextField(18);
tOldField.setText("要被替换的字段");
tNewField = new TextField(18);
tNewField.setText("替换字段");
b = new Button("确定");
ta = new TextArea(40, 80);
d = new Dialog(f, "提示信息", true);
d.setBounds(400, 250, 300, 250);
d.setLayout(new FlowLayout());
lab = new Label();
okB = new Button("确定");
d.add(lab);
d.add(okB);
event();
f.add(tDir);
f.add(tOldField);
f.add(tNewField);
f.add(b);
f.add(ta);
f.setVisible(true);
ta.requestFocusInWindow();
}
public void event() {
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
d.setVisible(false);
}
});
tDir.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
tDir.setText("");
}
});
tOldField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
tOldField.setText("");
}
});
tNewField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
tNewField.setText("");
}
});
tOldField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER)
bl = beforeRename();
if (bl) {
renameFile();
}
}
});
tNewField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER)
bl = beforeRename();
if (bl) {
renameFile();
}
}
});
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
bl = beforeRename();
if (bl) {
renameFile();
}
}
});
okB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
d.setVisible(false);
}
});
}
public Boolean beforeRename() {
if ("".equals(tDir.getText().trim()) || "".equals(tOldField.getText())) {
lab.setText("路径与旧字段不能为空");
d.setVisible(true);
return bl;
}
// 提示是否确认更改
String oldField = tOldField.getText().trim();
String newField = tNewField.getText();
int i = JOptionPane.showConfirmDialog(null, "确定将:" + oldField + " 替换为:"
+ newField + " ?");
// System.out.println(i);//查看i的值
if (i != 0)
return bl;
bl = true;
return bl;
}
private void renameFile() {
int count = 0;
File f = null;
String fileName = "";
String dirPath = tDir.getText();
String oldField = tOldField.getText();
String newField = tNewField.getText();
// JOptionPane.showConfirmDialog(null,
// "确定将"+oldField+"替换为"+newField+" ?");
File fileDir = new File(dirPath);
if (fileDir.exists() && fileDir.isDirectory()) {
ta.setText("");
String[] oldFileNames = fileDir.list();
for (String file : oldFileNames) {
/*
* 注意,这里一定要写成File(fl,file) 如果写成File(file)是行不通的, 一定要全路径
*/
f = new File(fileDir, file);
fileName = f.getName();
if (fileName.contains(oldField)) {
/*
* 这里可以反复使用replace替换, 当然也可以使用正则表达式来替换了
*/
f.renameTo(new File(fileDir.getAbsolutePath() + "//"
+ fileName.replace(oldField, newField)));
ta.append(fileName + "\r\n");
// System.out.println(fileName);//测试是否执行这块代码
count++;// 计数更改的文件数量
}
}
ta.append("更改了 " + count + " 个文件");
// System.out.println("更改了 "+count+" 个文件");
/*
* for(String name: fileNames){ System.out.println("操作前:"+name);
* if(name.indexOf("_黑马程序员_Android核心基础视频教程_")>0){
* System.out.println("文件名含有该字符串"+count++); newName=
* String.format("haha",name); } System.out.println("操作后:"+newName);
* ta.append(name+"\r\n"); }
*/
} else {
// String errorInfo= new String("输入的路径:"+dirPath+"错误");
lab.setText("输入的路径:" + dirPath + "错误");
d.setVisible(true);
}
}
public static void main(String[] args) {
new RenameTool();
}
}