JAVA自学经典例子(1-10)

JAVA自学经典例子

《JAVA自学经典例子》是一个从Python转JAVA的小猿的自学过程记录,没有打算从书上或者视频学起,纸上得来终觉浅呐!经过大量的人工代码和人工校正,记录下来自己的自学经典例子,希望能够与一起在学习JAVA的人同行(当然希望指出错误之处)。

  • Markdown和扩展Markdown简洁的语法
  • 代码块高亮
  • 图片链接和图片上传
  • LaTex数学公式
  • UML序列图和流程图
  • 离线写博客
  • 导入导出Markdown文件
  • 丰富的快捷键

例子1

实现继承类,实现一个多线程的继承类

package example17;

/**
 * Created by summing on 16/11/7.
 * Title: 继承Thread, 实现线程
 * Description: 通过继承
 */
public class oneThread extends Thread {

    /*
    * method: 继承Thead类必须实现的方法,当调用thread.start()方法时运行run()
    * */
    public void run() {
        System.out.println("one thread begining...");

        int flag = 0;
        while (true) {
            if (flag == 20) {
                System.out.println("one thread end...");
                break;
            }
            for (int i = 0; i < flag; i++) {
                System.out.print("*");
            }
            System.out.print("\n");
            flag++;

            try {
                sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new oneThread().start();
    }
}

例子2

使用正则表达式进行匹配,用到Pattern,Matcher,replaceAll。

package exmaple18;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by summing on 16/11/7.
 */
public class Replace1 {
    public static void main(String[] args) {
        String patt = "d[a-z]{1,}moon";

        String input = "Unix hath demoons and damoons, dymoons in it";
        System.out.println(input);

        Pattern r = Pattern.compile(patt);
        Matcher m = r.matcher(input);
        System.out.println("ReplaceALL: " + m.replaceAll("ddmon"));

        m.reset();
        StringBuffer sb = new StringBuffer();
        System.out.print("Append methods:");
        while (m.find()) {
            m.appendReplacement(sb, "ddmon");
        }

        // 与appendReplacement一起使用,把m匹配剩下的字符串复制到StringBuffer里
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
}

例子3

使用StringTokenizer类,返回分割符。使用到对象连续调用。

import java.util.StringTokenizer;

/**
 * Created by summing on 16/11/7.
 * Title: 使用StringTokenizer类
 * Description: 使用StringTokenizer类, 返回分隔符
 */
public class StrTok {
    public final static int MaxField = 7;
    public final static String Delim = "|";//分分隔符号

    // 处理一个字符串,返回一个由各个字符串域组成的数组
    public static String[] process(String line) {
        String[] results = new String[MaxField];

        StringTokenizer st = new StringTokenizer(line, Delim, true);

        // 获得每一个token
        int i = 0;
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            if (s.equals(Delim)) {
                i++;
                continue;
            }
            results[i] = s;
        }

        return results;
    }

    public static void printResult(String input, String[] outputs) {
        System.out.println("Input:" + input);
        for (int i = 0; i < outputs.length; i++)
            System.out.println("Output " + i + " was: " + outputs[i]);
    }


    public static void main(String[] args) {
        printResult("A|B|C|D||FFFF|G", process("A|B|C|D||FFFF|G"));
    }

}

例子4

字符串对齐方式。学习了构造函数,自定义函数,DecimalFormat和FieldPosition函数。

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;

/**
 * Created by summing on 16/11/7.
 * Method: 温度转换
 */
public class tempConverter {
    protected DecimalFormat df;
    protected FieldPosition fp;

    public static void main(String[] args) {
        tempConverter t = new tempConverter();
        t.start();
        t.data();
        t.end();
    }

    public tempConverter() {
        df = new DecimalFormat("#0.0");
        fp = new FieldPosition(NumberFormat.INTEGER_FIELD);
    }

    protected void print(float f, float c) {
        String fs = df.format(f, new StringBuffer(), fp).toString();
        fs = perpendSpace(4 - fp.getEndIndex(), fs);

        String cs = df.format(c, new StringBuffer(), fp).toString();
        cs = perpendSpace(4 - fp.getEndIndex(), cs);
        System.out.println(fs + " " + cs);
    }

    protected String perpendSpace(int n, String s) {
        String[] res = {"", " ", "  ", "   ", "    ", "     "};
        if (n < res.length)
            return res[n] + s;
        throw new IllegalStateException();
    }

    protected void start() {
        System.out.println("Fahr    Centigrade");
    }

    protected void data() {
        for (int i = -40; i <= 140; i += 10) {
            float c = (i - 32) * (5f / 9);
            print(i, c);
        }
    }

    protected void end() {
        System.out.println("------------------");
    }
}

例子5

格式化字符串。example input:

hi, i am your son.
Really? No kidding me.
You are so ugly.
Fuck off Dad.

转化成:

hi, i am your son. Really? No kidding me. You are so ugly. Fuck off Dad.

学习了多态的概念,in.readLine()字符串读入和Pipo的概念。

import java.io.*;
import java.util.StringTokenizer;

/**
 * Created by summing on 16/11/7.
 */
public class Fmt {
    public static final int COLWIDTH = 72;

    BufferedReader in;

    public static void main(String[] args) throws IOException {
        if (args.length == 1) {
            //System.out.println("args.length == 0");
            new Fmt(args[i]).format();
        } else
            System.out.println("Usage: java Fmt /dir/filename");

    }

    // 构造器,输入为文件名
    public Fmt(String fname) throws IOException {
        in = new BufferedReader(new FileReader(fname));
    }

    // 构造器,输入为字符串
    public Fmt(InputStream file) throws IOException {
        in = new BufferedReader(new InputStreamReader(file));
    }

    public void format() throws IOException {
        String w, f;
        int col = 0;
        while ((w = in.readLine()) != null) {

            // 空行
            if (w.length() == 0) {
                System.out.print("\n");//结束当前行
                if (col > 0) {
                    System.out.print("\n");//输出空行
                    col = 0;
                }
                continue;
            }

            if (w.equals("bye")) {
                System.exit(1);
            }

            // 不是空行, 格式化该行
            StringTokenizer st = new StringTokenizer(w);
            while (st.hasMoreTokens()) {
                f = st.nextToken();

                if ((col + f.length()) > COLWIDTH) {
                    System.out.print("\n");
                    col = 0;

                }
                System.out.print(f + " ");
                col += f.length() + 1;
            }
        }
        if (col > 0)
            System.out.print("\n");
        in.close();
    }
}

例子6

JAVA运行终端命令并输出


import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by summing on 16/8/7.
 * 方法说明:构造器,运行系统命令
 * 输入参数:String cmdline 命令字符
 * 返回类型:
 * 利用Java中Process类提供的方法让Java虚拟机截获被调用程序运行标准输出
 */
public class CmdExe {

    public CmdExe(String cmdline){
        try{
            String line;
            Process p = Runtime.getRuntime().exec(cmdline); //运行系统命令
            BufferedReader input = new BufferedReader(
                new InputStreamReader(p.getInputStream()));//使用缓存输出流获取屏幕输出

            while((line = input.readLine()) != null){//读取屏幕输出
                System.out.println("java print:" + line);
            }

            input.close();//关闭缓存输出
        }catch (Exception e){
            e.printStackTrace();//也是打印出异常,但是它还将显示出更深的调用信息
        }
    }

    public static void main(String args[]){
        new CmdExe("ls");
    }
}

例子7

实现一个简单的JAVA服务器的服务端和客户端程序。首先是写一个Server类,这个类用来监听8888端口,并从这个端口接收消息然后输出。然后是一个Client类,这个类连接上面启动的Server类,然后接收用户输入。

先运行Server后运行Client。

package example12;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * Created by summing on 16/8/7.
 * 服务器端
 */
public class SampleServer {
    public static void main(String[] args) throws Exception {
        //在8888端口建立一个服务器套接字 ServerSocket
        ServerSocket mySock = new ServerSocket(8888);
        //等待监听是否有客户端连接 waiting for client
        Socket sock = mySock.accept();
        //输入缓存
        BufferedReader in = new BufferedReader((
                new InputStreamReader(sock.getInputStream())));
        //输出缓存
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);

        System.out.println("Client say:" + in.readLine());
        out.println("I am Server, my port is 8888");
        sock.close();
    }
}
package example12;

import java.net.InetAddress;
import java.io.*;
import java.net.Socket;

/**
 * Created by summing on 16/8/7.
 * 用户端
 */
public class SimpleClient {

    public static void main(String[] args) throws Exception {
        //获取IP地址
        InetAddress addr = InetAddress.getLocalHost();
        String ipname = addr.getHostAddress();
        System.out.println(ipname);
        //打开8888端口,与服务器建立连接
        Socket sock = new Socket(ipname, 8888);

        //缓存输入 reader
        BufferedReader in = new BufferedReader((
                new InputStreamReader(sock.getInputStream())));
        //缓存输出 Writer
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);

        //向服务器发送信息 out to client
        out.println("hello my java client");
        //从服务器接收信息 in readline
        System.out.println(in.readLine());

        sock.close();
    }
}

例子8

多线程的JAVA客户端与服务器的建立与通信。服务器端:

package example13;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by summing on 16/9/7.
 * Title: 多线程服务器
 */

public class CompServer {
    public static void main(String[] args) throws Exception {
        //在8888端口建立一个服务器套接字 ServerSocket
        ServerSocket server = new ServerSocket(8888);
        System.out.println("Server starting...");

        while (true) {
            //等待监听是否有客户端连接 waiting for client
            Socket sk = server.accept();
            System.out.println("Accepting Connection...");

            //启动服务线程
            new ServerThread(sk).start();
        }
    }
}

//建立服务器线程,为多个客户端服务
class ServerThread extends Thread {
    private Socket sock;

    ServerThread(Socket sock) {
        this.sock = sock;
    }

    // 把需要并行处理的代码放在run()方法中
    // start()方法启动线程将自动调用 run()方法,这是由jvm的内存机制规定的
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try {

            in = new BufferedReader(
                    new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(sock.getOutputStream())), true);

            while (true) {
                //接收来自客户端的请求,根据不同的命令返回不同的信息
                String cmd = in.readLine();
                System.out.println("cmd:" + cmd);
                if (cmd == null) break;

                if (cmd.toUpperCase().startsWith("BYE")) {
                    out.println("Client say bye.");
                    break;
                } else {
                    out.println("Hello I am server!");
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            System.out.println("Closing Connection in Server...");
            //最后释放资源
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (sock != null) sock.close();
            } catch (IOException e) {
                System.out.println("close server err:" + e);
            }
        }
    }
}

客户端

package example13;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Created by summing on 16/9/7.
 * Title: 多线程客户端
 */
public class CompClient {
    //屏蔽本来应该静态访问,但是使用了对象访问的警告
    //suppress warnings relative to incorrect static access
    @SuppressWarnings("static-access")
    public static void main(String[] args) throws IOException, InterruptedException {
        InetAddress addr = InetAddress.getLocalHost();
        String addrIP = addr.getHostAddress();

        for (int i = 0; i < 10; i++) {
            new SocketThreadClient(addrIP);
        }

        Thread.currentThread().sleep(1000);
    }
}

class SocketThreadClient extends Thread {
    public static int count = 0;

    // 构造器,实现服务
    // 构造器就是和类名相同但无返回类型的方法, 构造器在类初始化的时候被调用通常被用来做一些初始化的工作
    public SocketThreadClient(String addrIP) {
        count++;
        BufferedReader in = null;
        PrintWriter out = null;
        Socket sock = null;

        try {
            sock = new Socket(addrIP, 8888);

            in = new BufferedReader(
                    new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(sock.getOutputStream())), true);

            // 向服务器发送请求
            System.out.println("count:" + count);
            out.println("I am Client, coming");
            System.out.println(in.readLine());
            out.println("Client say byebye");
            System.out.println(in.readLine());

        } catch (IOException e) {
            System.out.println(e);
        } finally {
            out.println("Client End");

            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (sock != null) sock.close();

            } catch (IOException e) {
                System.out.println("close client error:" + e);
            }

        }
    }
}

例子9

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * Created by summing on 16/10/7.
 * Title: 获取一个URL文本
 * Description: 通过使用URL类,构造一个输入对象,并读取其内容。
 */
public class getURL {
    public static void main(String[] args) {
        String URL = "http://www.baidu.com";
        //运行该实体类
        new getURL(URL);
    }

    /*
    * 方法说明: 构造器
    * 输入参数: String URL 网址
    * 返回类型: none
    * */
    public getURL(String URL) {
        try {
            //创建一个URL对象
            URL url = new URL(URL);
            //读取从服务器返回的所有文本
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(url.openStream()));

            String str;
            while ((str = in.readLine()) != null) {
                display(str);
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 方法说明: 显示提取URI信息
    * */
    private void display(String s) {
        if (s != null) {
            System.out.println(s);
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值