ラベル java の投稿を表示しています。 すべての投稿を表示
ラベル java の投稿を表示しています。 すべての投稿を表示

2019年4月13日土曜日

Java 練習

java 練習

import java.util.*;

class demo1 {
public static void main(String[] args) {
int x = 123456789;
StringBuffer b = new StringBuffer();
while (x != 0) {
int t = x % 10;
x = (x - t) / 10;
b.append(t + ",");
}
System.out.println(b);
}
}

//
C:\>java demo1
9,8,7,6,5,4,3,2,1,

2019年3月28日木曜日

Math.random()

 Math.random()

指定范围内乱数。

import java.util.*;
class random {
public static void main(String[] args) {
double temp = Math.random();
System.out.println(temp);
System.out.println(temp * (500 - 600));
System.out.println((int)(temp * (500 - 600) + 600));
System.out.println(Math.random() * (5 - 10) + 10);
}
}

2018年10月23日火曜日

アルファベットArrayList作成

import java.util.*;

class chart {
public static void main(String[] args) {
ArrayList<String> keyList = new ArrayList<>();
for (int i = 0x41; i < 0x5B; i++) {
keyList.add(String.valueOf((char)i));
}

for (int i = 0x30; i < 0x3A; i++) {
keyList.add(String.valueOf((char)i));
}

System.out.println(keyList);


String x = keyList.toString();
char[] temp = x.toCharArray();
temp = x.toCharArray();
for (char cc : temp) {
System.out.println(cc);
}

StringBuffer temp2 = new StringBuffer();

for(String xx :keyList){
temp2.append(xx);
}

System.out.println(temp2);
}
}

2018年7月19日木曜日

java_Semaphore

java_Semaphore

import java.util.concurrent.Semaphore;
import java.lang.System;

class  M180717_Semaphore {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(8);
long s = System.currentTimeMillis();

A a = new A(semaphore);
a.start();

B b = new B(semaphore);
b.start();

B b2 = new B(semaphore);
b2.start();
}
}

class A extends Thread {
private Semaphore semaphore;
public A(Semaphore semaphore) {
this.semaphore = semaphore;
}

@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "-------");
for (int i = 0 ; i < 99 ; i++) {
System.out.print("a");
}
semaphore.release();
} catch (Exception e) {
System.out.println(semaphore.getQueueLength());
}
}
}

class B extends Thread {
private Semaphore semaphore;

public B(Semaphore semaphore) {
this.semaphore = semaphore;
}

@Override
public void run() {
try {
// System.out.println(semaphore.getQueueLength());
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "-------");
for (int i = 0 ; i < 99 ; i++) {
System.out.print("b");
}
semaphore.release();
} catch (Exception e) {
System.out.println(semaphore.getQueueLength());
}
}
}

class C extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-------");
for (int i = 0 ; i < 99 ; i++) {
System.out.print("c");
}
}
}

class X implements Runnable {
@Override
public void run() {
System.out.println("xxxxx");
}
}


2017年6月26日月曜日

Java Timer

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

public class Main {
    public static int x;
    public static void main(String[] args) throws Exception {
        x = 30 * 60 + 9;
        System.out.println(x);
        while(x != 0){
            x = x -1;
            show();
        }    
    }
   
    public static void show(){
        int hh = x /60;
        int ss = x - hh * 60;
        int hht1 = hh % 100 /10;
        int hht2 = hh % 10;
        int sst1 = ss % 100 /10;
        int sst2 = ss % 10;
        System.out.println("--------------");
        System.out.print(hht1);
        System.out.print(hht2);
        System.out.print(sst1);
        System.out.println(sst2);
        System.out.println("--------------");
    }
}

https://paiza.io/projects/FJ_pxjUT07pv51Ab7TWA4w


2017年4月24日月曜日

Java interface Callback 2

Java interface Callback 2


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

public class Main {

    public static void main(String[] args) throws Exception{
        T1 t = new T1();
        try{
            Thread.sleep(1000);
        }catch(Exception e){
           
        }
        t.st();
    }
}

class T1 implements onTest{
    public Oset o;
    public T1(){
        o = new Oset();
        o.setont(this);
    }
   
    public void st(){
        o.methods();
    }
   
    public void getx(){
        System.out.println("--------implements onTest--------");
    }
}

interface onTest{
    public void getx();
}

class Oset {
    private onTest ont;
    public void setont(onTest ont){
        this.ont = ont;
    }
   
    public void methods(){
        System.out.println("--------------methods------------------");
        ont.getx();
    }
}


Demo
https://paiza.io/projects/l2lBiluXHzRmjoKsj-cLBA

Java interface Callback

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

public class Main {
    public static void main(String[] args) throws Exception {
    Oset oset = new Oset();
    oset.setont(new onTest(){
        public void getx(){
            System.out.println("----------------interface Callback---------------");
        }
    });

    try{
        Thread.sleep(1000);
    }catch(Exception e){
     
    }
    oset.methods();
    }
}


interface onTest{
    public void getx();
}

class Oset {
    private onTest ont;
    public void setont(onTest ont){
        this.ont = ont;
    }
 
    public void methods(){
        System.out.println("--------------methods------------------");
        ont.getx();
    }
}

Demo
https://paiza.io/projects/uWqAgbv37VXi3LEWkS4WlQ


2017年4月23日日曜日

Thread.activeCount()

Thread.activeCount()
返回当前线程的线程组中活动线程的数目。

public class T2 {
        public static void main(String[] args) {
                new Thread(new Runnable() {
                        public void run() {
                                while (true) {
                                        // System.out.println(1);
                                }
                        }
                }).start();
                new Thread(new Runnable() {
                        public void run() {
                                while (true) {
                                        // System.out.println(2);
                                }
                        }
                }).start();
                new Thread(new Runnable() {
                        public void run() {
                                while (true) {
                                        // System.out.println(3);
                                }
                        }
                }).start();
                System.out.println(Thread.activeCount());
        }
}

2017年4月11日火曜日

Java ArrayList to String[]

Java ArrayList to String[]

https://paiza.io/projects/3F_iZEjxHh9AUNgPwAohxA

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) throws Exception {
        ArrayList<String> sl = new ArrayList<String>();
        sl.add("a");
        sl.add("b");
        sl.add("c");
       
        String[] temp = sl.toArray(new String[]{});
       
        System.out.println(temp.length);
        for( String x:temp){
            System.out.println(x);
        }
    }
}

2017年4月2日日曜日

Java FilenameFilter

Java FilenameFilter


    public void test() {
        File file = new File(Environment.getExternalStorageDirectory().toString());
        String[] files = file.list(new MusicFilter());
        if (files.length > 0) {
            for (String name : files) {
                System.out.println(name);
            }
        }

        String[] files2 = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".mp3") || name.endsWith(".wav")) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        if (files2.length > 0) {
            for (String name : files2) {
                System.out.println(name);
            }
        }
    }

    public class MusicFilter implements FilenameFilter {

        @Override
        public boolean accept(File dir, String name) {
            if (name.endsWith(".mp3") || name.endsWith(".wav")) {
                return true;
            } else {
                return false;
            }
        }
    }

2017年2月28日火曜日

Java CallBack 练习

Java CallBack 练习

https://paiza.io/projects/J4kb3mqHFWTylgPFh_q-sw

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

public class Main {
    public static void main(String[] args) throws Exception {
        Text1 tt1 = new Text1();
        tt1.t1(new Text1.CallBack(){
            public void gets(String x){
                System.out.println(x);
            }
            public void gety(String y){
                System.out.println(y);
            }
        });
    }
}

class Text1{
    interface CallBack{
        public void gets(String x);
        public void gety(String y);
    }

    public void t1( CallBack cb){
        int i = 6;
        for(; i < 200; i++){
        }
        if(i%2 == 0){
            cb.gets("x" + i + "");
        }else{
            cb.gety("y" + i + "");
        }
    }
}

2017年1月16日月曜日

Java 回调

Java 回调

https://paiza.io/projects/3KFF7-6l4pA4pvijDyvPiw

public class CB2 {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                CBB2 cb = new CBB2();
                cb.tt(new CBB2.CallBack() {
                     
                        @Override
                        public void start() {
                                // TODO Auto-generated method stub
                                System.out.println(Thread.currentThread().getName());
                        }
                });
        }

}

class CBB2{
        public interface CallBack{
                public void start();
        }
     
        public void tt(CallBack cb){
                t1 tt1 = new t1(cb);
                tt1.start();
        }
     
        public class t1 extends Thread{
                private CallBack cb;
             
                public t1(CallBack cb) {
                        this.cb = cb;
                }
             
                public void run(){
                        try {
                                Thread.sleep(3000);
                        } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        cb.start();
                }
        }
}

2017年1月12日木曜日

Java 线程同步。

Java 线程同步。
要锁定都一个资源。

public class T1 {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                TX re = new TX();
                T2 t2 = new T2(re);
                Thread t = new Thread(t2);
                t.start();

                T3 t3 = new T3(re);
                Thread tt = new Thread(t3);
                tt.start();
        }
}

class TX {
        public String name;
        public String sex;
}

class T2 implements Runnable {
        private TX r;

        public T2(TX r) {
                this.r = r;
        }

        @Override
        public void run() {
                // TODO Auto-generated method stub
                int i = 0;
                while (true) {
                        synchronized (r) {
                                if (i == 0) {
                                        r.name = "AAAA";
                                        r.sex = "FFFFF";
                                } else {
                                        r.name = "BBB";
                                        r.sex = "mmmmmmmmmmmmmmmmmmmm";
                                }
                        }
                        i = (i + 1) % 2;
                }
        }
}

class T3 implements Runnable {
        private TX r;

        public T3(TX r) {
                this.r = r;
        }

        @Override
        public void run() {
                // TODO Auto-generated method stub
                while (true) {
                        synchronized (r) {
                                System.out.println(r.name + "---------" + r.sex);
                        }
                }
        }
}

2016年12月8日木曜日

Java FTP Socket

Java FTP Socket

添加对文件夹的处理。







import java.io.*;
import java.net.*;

/*
file:///E:/api/index.html
*/

class Tsocket {
public static void main(String[] args) {
try {
// File[] fs = new File[] {new File("Sublime Text Build 3114 x64.zip"), new File("Sublime Text Build 3114 x64 (2).zip"), new File("npp.6.9.2.bin.zip"), new File("Sublime Text Build 3114.zip")};

File f = new File("E:\\Android");
File[] fs = f.listFiles() ;

// UFTP u = new UFTP("xxxx.web.fc2.com", "xxxx", "xxxx");
UFTP u = new UFTP("192.168.11.7", "guest", "guest");
String code = u.FTPconnect();

if (code.equals("ConnectFTPServer")) {
u.upload(fs);
u.close();
System.out.println(code);
} else {
System.out.println(code);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}



class UFTP {
private String USER, PASSWORD;
private InetAddress FTPServerIP;
private BufferedReader FTPCmdreader;
private BufferedWriter FTPCmdwriter ;

public UFTP(String FURL, String USER, String PASSWORD) throws Exception {
this.FTPServerIP = InetAddress.getByName(FURL);
this.USER = USER;
this.PASSWORD = PASSWORD;
}

public  String FTPconnect()  {
String errorlevel = "ConnectFTPServer";
try {
Socket socket21 = new Socket (FTPServerIP, 21);
FTPCmdreader = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
FTPCmdwriter = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
FTPcommand(FTPCmdwriter, "USER " + USER);
FTPcommand(FTPCmdwriter, "PASS " + PASSWORD);
} catch (Exception e) {
errorlevel = "ConnectFTPerror";
}
return errorlevel;
}

public void upload(File[] files) throws Exception {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
FTPcommand(FTPCmdwriter, "PASV ");
String[] temp = new String[] {};
String recode = new String();
while (true) {
recode = FTPCmdreader.readLine();
System.out.println(recode);
if (recode.substring(0, 3).equals("227")) {
temp = get227(recode);
break;
}
}
Socket socket20 = new Socket(temp[0], Integer.parseInt(temp[1]));
OutputStream ftpOutputStream = socket20.getOutputStream();
FileInputStream upfileInputStream = new FileInputStream(files[i]);
FTPcommand(FTPCmdwriter, "TYPE " + "I");
FTPcommand(FTPCmdwriter, "STOR " + files[i].getName());
System.out.println("UPDATE Filename " + files[i].getName());
byte[] buff = new byte[1024 * 1024];
int len = 0;
while ( (len = upfileInputStream.read(buff) ) != -1) {
ftpOutputStream.write(buff, 0, len);
ftpOutputStream.flush();
System.out.print("*");
}
ftpOutputStream.close();
upfileInputStream.close();
System.out.println("");
Thread.sleep(5 * 1000);
}
}
}

public void close() {
try {
FTPcommand(FTPCmdwriter, "QUIT ");
String temp = null;
while ( (temp = FTPCmdreader.readLine() ) != null) {
System.out.println(temp);
}
System.out.println("");
FTPCmdwriter.close();
FTPCmdreader.close();
} catch (Exception e) {

}
}
private void FTPcommand(BufferedWriter FTPCmdwriter, String FTPcmd) throws Exception {
FTPCmdwriter.write(FTPcmd +  "\r\n");
FTPCmdwriter.flush();
}

protected String[] get227(String string) {
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
String[] temp = substring.split(",");
String ip = temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3];
int port = Integer.parseInt(temp[4]) * 256 + Integer.parseInt(temp[5]);
String sport = String.valueOf(port);
String[] res = {ip, sport};
return res;
}
}

2016年12月3日土曜日

Java Socket 连接

Java Socket 连接





import java.net.*;
import java.io.*;

public class main {
public static void main(String[] args) {
TserverSocket();
}

public static void TserverSocket() {
try {
int port = 1024;
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket soc = ss.accept();
System.out.println(soc);
OutputStream os = soc.getOutputStream();
OutputStreamWriter oos = new OutputStreamWriter(os);
System.out.println("server accept");
for (int i = 0; i < 1024; i++) {
oos.write(i);
oos.flush();
}
oos.close();
}
} catch (Exception e) {
}
}
}





import java.io.*;
import java.net.*;

class main {
public static void main(String[] args) {
client();
}

public static void client() {
try {
Socket s = new Socket("192.168.11.107", 1024);
InputStream is = s.getInputStream();
InputStreamReader iis = new InputStreamReader(is);
int i = 0;
while ( (i = iis.read() ) != -1 ) {
System.out.println(i);
}
System.out.println(s);
iis.close();

} catch (Exception e) {

}
}
}

2016年11月30日水曜日

Java BackCall 的返回值运行在新的Thread上。

Java BackCall 的返回值运行在新的Thread上。

所以,在Android 上不能咋 BackCall上更新 主线程。


https://paiza.io/projects/dBt6EFZZnt8GdS0MDW8I-g



import java.io.*;
import java.net.*;

public class Main {
        public static void main(String[] args) throws Exception {
                // Here your code !
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line = br.readLine();
                Handel h = new Handel();
                System.out.println("Call by BackCall thread name >>" + Thread.currentThread().getName());
                h.Down(new Handel.BackCall() {
                        public void restout(String xx) {
                                System.out.println("BackCall thread name >>" + Thread.currentThread().getName());
                                System.out.println(xx);
                        }
                });
        }
}

class Handel {
        public interface BackCall {
                public void restout (String json);
        }
        public void Down(BackCall bc) {
                new Thread(new Runnable() {
                        public void run() {
                                try {
                                        URL u = new URL("http://www.yahoo.co.jp");
                                        HttpURLConnection c = (HttpURLConnection)u.openConnection();
                                        c.setConnectTimeout(3000);
                                        c.setReadTimeout(3000);
                                        c.setDoInput(true);
                                        c.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.6) Gecko/20040225 Firefox/0.8");
                                        InputStream is = null;
                                        c.setRequestMethod("GET");
                                        String bbb = "";
                                        if (c.getResponseCode() == 200) {
                                                is = c.getInputStream();
                                                BufferedReader br = new BufferedReader( new InputStreamReader(is));
                                                bbb = br.readLine();
                                        }
                                        bc.restout(bbb);
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                } ).start();
        }
}

2016年11月20日日曜日

java 字符串分割,得到文件名

java 字符串分割
得到URL的文件名

public class test {

public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg";
String[] sa = s.split("/");
System.out.println(sa[sa.length-1]);
}

}

2016年11月14日月曜日

Java HashMap 遍历 练习

Java HashMap 遍历 练习



    protected void HSM() {
        Map<String, String> x = new HashMap<String, String>();
        x.put("a", "aa");
        x.put("b", "bb");
        x.put("c", "cc");
        x.put("d", "dd");
        System.out.println(x);

        System.out.println("1111111111111111");
        Set<String> setk = x.keySet();
        Iterator ite = setk.iterator();
        while (ite.hasNext()) {
            String temp = (String) ite.next();
            System.out.println(temp);
            System.out.println(x.get(temp));
        }


        System.out.println("22222222222222");
        for (String String : setk) {
            System.out.println(String);
            System.out.println(x.get(String));
        }
    }

2016年11月9日水曜日

Thread 練習

Thread 練習

https://paiza.io/projects/xrf-cg825CeFPxNDEjnKlg


import java.io.*;
import java.net.*;

public class Main {
public static void main(String[] args) throws Exception {
int i = 0;
for (i = 0; i < 90; i++) {
new Thread(new Runnable() {
public void run() {
long x = Thread.currentThread().getId();
new D().Down(x);
}
} ).start();
}
}
}

class D {
public D() {
}
public void Down(Long x) {
try {
URL u = new URL("http://www.yahoo.co.jp");
HttpURLConnection c = (HttpURLConnection)u.openConnection();
c.setConnectTimeout(3000);
c.setReadTimeout(3000);
c.setDoInput(true);
InputStream is = null;
c.setRequestMethod("GET");
if (c.getResponseCode() == 200) {
is = c.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
System.out.println(Thread.currentThread().getName() + "  :  " + br.readLine());
// byte[] buf = new byte[1024];
// int len = 0;
// while((len = is.read(buf)) != -1 ){
//     System.out.println("Thread:"+ x +"->"+ new String(buf,0,len));
//     System.out.println(x);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

2016年11月7日月曜日

字节流转换字符流

字节流转换字符流




public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new XML().execute("null");
    }

    public class XML extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
//                URL u = new URL("http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip");
                URL u = new URL("http://cdefgab.web.fc2.com/song.json");
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");
//                字节流转换字符流方法
//                if(huc.getResponseCode() == 200) {
//                    BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream(),"utf-8"));
//                    InputStream is = huc.getInputStream();
//                    InputStreamReader isr = new InputStreamReader(is,"utf-8");
//                    BufferedReader br = new BufferedReader(isr);
//                    String temp = null;
//                    while((temp = br.readLine()) != null){
//                        System.out.println("--------------");
//                        System.out.println(temp);
//                    }
//                }

//                字节流缓冲方法
                if (huc.getResponseCode() == 200) {
                    System.out.println("-----Astart");
                    BufferedInputStream bis = new BufferedInputStream(huc.getInputStream());
                    int i = 0;
                    byte[] buff = new byte[1024];
                    while ((i = bis.read(buff)) != -1) {
                        System.out.println("deta.length--" + i);
                        System.out.println(new String(buff, 0, i));
                    }
                    System.out.println("-----Aend");
                }

                if (huc.getResponseCode() == 200) {
                    System.out.println("-----Bstart");
                    InputStream is = huc.getInputStream();
                    byte[] buff = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buff)) != -1) {
                        System.out.println("data.lenght" + len);
                        System.out.println(new String(buff, 0, len));
                    }
                    System.out.println("-----Bend");
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}