Android 外部存储
https://developer.android.com/guide/topics/data/data-storage.html
protected void saveto() {
// I/System.out: this.getDatabasePath("test")
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
File f1 = this.getDatabasePath("test");
System.out.println("this.getDatabasePath(\"test\")");
System.out.println(f1.getAbsolutePath());
System.out.println(f1.getPath());
System.out.println(f1.toString());
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
File f2 = this.getExternalFilesDir(null);
System.out.println("this.getExternalFilesDir(null)");
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getPath());
System.out.println(f2.toString());
// I/System.out: /data
// I/System.out: /data
// I/System.out: /data
File f3 = Environment.getDataDirectory();
System.out.println("Environment.getDataDirectory()");
System.out.println(f3.getAbsolutePath());
System.out.println(f3.getPath());
System.out.println(f3.toString());
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
File f4 = Environment.getExternalStorageDirectory();
System.out.println("Environment.getExternalStorageDirectory()");
System.out.println(f4.getAbsolutePath());
System.out.println(f4.getPath());
System.out.println(f4.toString());
}
2016年12月25日日曜日
2016年12月24日土曜日
Android IntentService 类
Android IntentService 类
https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件
//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e560.m1217a">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServer"></service>
</application>
</manifest>
//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button bt = new Button(this);
bt.setText("SaveFiletoAndroidFile");
linearLayout.addView(bt);
setContentView(linearLayout);
i = 0;
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
SavetoServer(i);
}
});
}
protected void SavetoServer(int i) {
String[] imgURLs = new String[]{
"https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
};
Intent intent = new Intent(this, MyServer.class);
intent.putExtra("URL", imgURLs[i].toString());
startService(intent);
}
}
https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件
//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e560.m1217a">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServer"></service>
</application>
</manifest>
//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button bt = new Button(this);
bt.setText("SaveFiletoAndroidFile");
linearLayout.addView(bt);
setContentView(linearLayout);
i = 0;
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
SavetoServer(i);
}
});
}
protected void SavetoServer(int i) {
String[] imgURLs = new String[]{
"https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
};
Intent intent = new Intent(this, MyServer.class);
intent.putExtra("URL", imgURLs[i].toString());
startService(intent);
}
}
//////////////////////////////////////////////////////////////////////
import android.app.IntentService;
import android.content.Intent;
public class MyServer extends IntentService {
public MyServer() {
super("test");
}
@Override
protected void onHandleIntent(Intent intent) {
HTTPClient httpClient = new HTTPClient(getApplicationContext(), intent.getStringExtra("URL"));
}
}
//////////////////////////////////////////////////////////////////////
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HTTPClient {
private String urlString;
private String FileName;
private String savePath;
private Context context;
public HTTPClient(Context context, String urlString) {
this.context = context;
this.urlString = urlString.replace("\\", "");
this.savePath = String.valueOf(this.context.getFilesDir());
FileName = getFname(urlString);
System.out.println("Thread.name Httpclient" + Thread.currentThread().getName());
SaveFile();
}
public void SaveFile() {
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5 * 1000);
httpURLConnection.setReadTimeout(5 * 1000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
if (httpURLConnection.getResponseCode() == 200) {
File SaveF = new File(this.savePath + "/" + this.FileName);
InputStream inputStream = httpURLConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(SaveF);
byte[] buff = new byte[4096];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
fos.write(buff, 0, len);
fos.flush();
}
fos.close();
inputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected String getFname(String url) {
String[] temp = url.split("/");
return temp[temp.length - 1];
}
}
2016年12月9日金曜日
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;
}
}
添加对文件夹的处理。
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月5日月曜日
FTP命令 FTP响应码
FTP命令
命令 | 描述 |
ABOR | 中断数据连接程序 |
ACCT <account> | 系统特权帐号 |
ALLO <bytes> | 为服务器上的文件存储器分配字节 |
APPE <filename> | 添加文件到服务器同名文件 |
CDUP <dir path> | 改变服务器上的父目录 |
CWD <dir path> | 改变服务器上的工作目录 |
DELE <filename> | 删除服务器上的指定文件 |
HELP <command> | 返回指定命令信息 |
LIST <name> | 如果是文件名列出文件信息,如果是目录则列出文件列表 |
MODE <mode> | 传输模式(S=流模式,B=块模式,C=压缩模式) |
MKD <directory> | 在服务器上建立指定目录 |
NLST <directory> | 列出指定目录内容 |
NOOP | 无动作,除了来自服务器上的承认 |
PASS <password> | 系统登录密码 |
PASV | 请求服务器等待数据连接 |
PORT <address> | IP 地址和两字节的端口 ID |
PWD | 显示当前工作目录 |
QUIT | 从 FTP 服务器上退出登录 |
REIN | 重新初始化登录状态连接 |
REST <offset> | 由特定偏移量重启文件传递 |
RETR <filename> | 从服务器上找回(复制)文件 |
RMD <directory> | 在服务器上删除指定目录 |
RNFR <old path> | 对旧路径重命名 |
RNTO <new path> | 对新路径重命名 |
SITE <params> | 由服务器提供的站点特殊参数 |
SMNT <pathname> | 挂载指定文件结构 |
STAT <directory> | 在当前程序或目录上返回信息 |
STOR <filename> | 储存(复制)文件到服务器上 |
STOU <filename> | 储存文件到服务器名称上 |
STRU <type> | 数据结构(F=文件,R=记录,P=页面) |
SYST | 返回服务器使用的操作系统 |
TYPE <data type> | 数据类型(A=ASCII,E=EBCDIC,I=binary) |
USER <username>> | 系统登录的用户名 |
FTP响应码
响应代码 | 解释说明 |
110 | 新文件指示器上的重启标记 |
120 | 服务器准备就绪的时间(分钟数) |
125 | 打开数据连接,开始传输 |
150 | 打开连接 |
200 | 成功 |
202 | 命令没有执行 |
211 | 系统状态回复 |
212 | 目录状态回复 |
213 | 文件状态回复 |
214 | 帮助信息回复 |
215 | 系统类型回复 |
220 | 服务就绪 |
221 | 退出网络 |
225 | 打开数据连接 |
226 | 结束数据连接 |
227 | 进入被动模式(IP 地址、ID 端口) |
230 | 登录因特网 |
250 | 文件行为完成 |
257 | 路径名建立 |
331 | 要求密码 |
332 | 要求帐号 |
350 | 文件行为暂停 |
421 | 服务关闭 |
425 | 无法打开数据连接 |
426 | 结束连接 |
450 | 文件不可用 |
451 | 遇到本地错误 |
452 | 磁盘空间不足 |
500 | 无效命令 |
501 | 错误参数 |
502 | 命令没有执行 |
503 | 错误指令序列 |
504 | 无效命令参数 |
530 | 未登录网络 |
532 | 存储文件需要帐号 |
550 | 文件不可用 |
551 | 不知道的页类型 |
552 | 超过存储分配 |
553 | 文件名不允许 |
Android FTP 文件上传
Android FTP 文件上传
package com.example.e560.m1126a.ToolsClass;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by E560 on 2016/12/04.
*/
public class sun_FTP {
private String ftp_url, ftp_user, ftp_password;
private boolean ftp_open;
private String TAG = "sun_FTP";
public sun_FTP(String ftp_url, String ftp_user, String ftp_password) {
this.ftp_url = ftp_url;
this.ftp_user = ftp_user;
this.ftp_password = ftp_password;
this.ftp_open = true;
}
public void Ftp_connect(String file_mode, File file) throws IOException {
InetAddress inetAddress = InetAddress.getByName(ftp_url);
Socket socket21 = new Socket(inetAddress.getHostAddress(), 21);
BufferedReader ftpcmd_input = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
BufferedWriter ftpcmd_output = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
sendFTPcommand(ftpcmd_output, "USER " + ftp_user);
sendFTPcommand(ftpcmd_output, "PASS " + ftp_password);
sendFTPcommand(ftpcmd_output, "PASV ");
switch (file_mode) {
case "upFile":
while (ftp_open) {
String temp = ftpcmd_input.readLine();
Log.i(TAG, temp);
String code = temp.substring(0, 3);
//进入被动模式(IP 地址、ID 端口)
if (code.equals("227")) {
String[] temp2 = get227(temp);
sendFTPcommand(ftpcmd_output, "TYPE " + "I");
sendFTPcommand(ftpcmd_output, "STOR " + file.getName());
upFile(temp2, file);
sendFTPcommand(ftpcmd_output, "QUIT");
ftpcmd_output.
}
}
break;
case "downFile":
break;
case "Del_file":
break;
}
}
private void upFile(String[] urltemp, File file) throws IOException {
Socket dataSocket = new Socket(urltemp[0], Integer.parseInt(urltemp[1]));
OutputStream outputStream = dataSocket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buff = new byte[20480];
int len = 0;
while ((len = fileInputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
dataSocket.close();
ftp_open = false;
}
protected void sendFTPcommand(BufferedWriter ftpcmd_output, String command) throws IOException {
ftpcmd_output.write(command + "\r\n");
ftpcmd_output.flush();
if (command.equals("QUIT")) {
ftpcmd_output.close();
}
}
protected Socket ftpSocket() throws IOException {
Socket socket = new Socket(ftp_url, 21);
return null;
}
protected String[] get227(String string) {
//227 Entering Passive Mode (208,71,106,43,237,147).
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
Log.i(TAG, substring);
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);
Log.i(TAG, "POST " + port);
String[] res = {ip, sport};
return res;
}
}
package com.example.e560.m1126a.ToolsClass;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by E560 on 2016/12/04.
*/
public class sun_FTP {
private String ftp_url, ftp_user, ftp_password;
private boolean ftp_open;
private String TAG = "sun_FTP";
public sun_FTP(String ftp_url, String ftp_user, String ftp_password) {
this.ftp_url = ftp_url;
this.ftp_user = ftp_user;
this.ftp_password = ftp_password;
this.ftp_open = true;
}
public void Ftp_connect(String file_mode, File file) throws IOException {
InetAddress inetAddress = InetAddress.getByName(ftp_url);
Socket socket21 = new Socket(inetAddress.getHostAddress(), 21);
BufferedReader ftpcmd_input = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
BufferedWriter ftpcmd_output = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
sendFTPcommand(ftpcmd_output, "USER " + ftp_user);
sendFTPcommand(ftpcmd_output, "PASS " + ftp_password);
sendFTPcommand(ftpcmd_output, "PASV ");
switch (file_mode) {
case "upFile":
while (ftp_open) {
String temp = ftpcmd_input.readLine();
Log.i(TAG, temp);
String code = temp.substring(0, 3);
//进入被动模式(IP 地址、ID 端口)
if (code.equals("227")) {
String[] temp2 = get227(temp);
sendFTPcommand(ftpcmd_output, "TYPE " + "I");
sendFTPcommand(ftpcmd_output, "STOR " + file.getName());
upFile(temp2, file);
sendFTPcommand(ftpcmd_output, "QUIT");
ftpcmd_output.
}
}
break;
case "downFile":
break;
case "Del_file":
break;
}
}
private void upFile(String[] urltemp, File file) throws IOException {
Socket dataSocket = new Socket(urltemp[0], Integer.parseInt(urltemp[1]));
OutputStream outputStream = dataSocket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buff = new byte[20480];
int len = 0;
while ((len = fileInputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
dataSocket.close();
ftp_open = false;
}
protected void sendFTPcommand(BufferedWriter ftpcmd_output, String command) throws IOException {
ftpcmd_output.write(command + "\r\n");
ftpcmd_output.flush();
if (command.equals("QUIT")) {
ftpcmd_output.close();
}
}
protected Socket ftpSocket() throws IOException {
Socket socket = new Socket(ftp_url, 21);
return null;
}
protected String[] get227(String string) {
//227 Entering Passive Mode (208,71,106,43,237,147).
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
Log.i(TAG, substring);
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);
Log.i(TAG, "POST " + 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) {
}
}
}
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年12月2日金曜日
Android 网络信息和IP地址
Android 网络信息和IP地址
package com.example.java.m1202a;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(this.getClass().getCanonicalName());
test_network();
test_ipadd();
}
/**
* <uses-permission android:name="android.permission.INTERNET"/>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
*/
protected void test_network() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
System.out.println("toString " + networkInfo.toString());
System.out.println("getType " + networkInfo.getType());
System.out.println("getTypeName " + networkInfo.getTypeName());
System.out.println("getState " + networkInfo.getState());
System.out.println("getDetailedState " + networkInfo.getDetailedState());
System.out.println("getReason " + networkInfo.getReason());
System.out.println("getSubtypeName " + networkInfo.getSubtypeName());
System.out.println("getExtraInfo " + networkInfo.getExtraInfo());
System.out.println("describeContents " + networkInfo.describeContents());
System.out.println(networkInfo.getClass().getCanonicalName());
}
protected void test_ipadd() {
System.out.println("test_ipadd 7777");
try {
Enumeration<NetworkInterface> networkInterfaces = null;
networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface2 = networkInterfaces.nextElement();
Enumeration<InetAddress> ipadd = networkInterface2.getInetAddresses();
while (ipadd.hasMoreElements()) {
System.out.println(ipadd.nextElement().toString());
}
}
System.out.println(networkInterfaces.getClass().getCanonicalName());
} catch (SocketException e) {
e.printStackTrace();
}
}
}
package com.example.java.m1202a;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(this.getClass().getCanonicalName());
test_network();
test_ipadd();
}
/**
* <uses-permission android:name="android.permission.INTERNET"/>
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
*/
protected void test_network() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
System.out.println("toString " + networkInfo.toString());
System.out.println("getType " + networkInfo.getType());
System.out.println("getTypeName " + networkInfo.getTypeName());
System.out.println("getState " + networkInfo.getState());
System.out.println("getDetailedState " + networkInfo.getDetailedState());
System.out.println("getReason " + networkInfo.getReason());
System.out.println("getSubtypeName " + networkInfo.getSubtypeName());
System.out.println("getExtraInfo " + networkInfo.getExtraInfo());
System.out.println("describeContents " + networkInfo.describeContents());
System.out.println(networkInfo.getClass().getCanonicalName());
}
protected void test_ipadd() {
System.out.println("test_ipadd 7777");
try {
Enumeration<NetworkInterface> networkInterfaces = null;
networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface2 = networkInterfaces.nextElement();
Enumeration<InetAddress> ipadd = networkInterface2.getInetAddresses();
while (ipadd.hasMoreElements()) {
System.out.println(ipadd.nextElement().toString());
}
}
System.out.println(networkInterfaces.getClass().getCanonicalName());
} catch (SocketException e) {
e.printStackTrace();
}
}
}
2016年12月1日木曜日
Android 保存 GridView 的位置
保存 GridView 的位置
gridView.getFirstVisiblePosition();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex("name"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
Toast.makeText(ListPage.this, img_url, Toast.LENGTH_SHORT).show();
grp = gridView.getFirstVisiblePosition();
Intent intent = new Intent(getApplicationContext(), Idolpiclist.class);
intent.putExtra("name", name);
startActivity(intent);
}
});
private class Myhand extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
cursor = (Cursor) msg.obj;
System.out.println(cursor.getCount());
GridView gridView = (GridView) findViewById(R.id.List_page_gridview);
gridView.setSelection(grp+1);
gridView.setAdapter(new Myadapter());
}
}
gridView.getFirstVisiblePosition();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
cursor.moveToPosition(position);
String name = cursor.getString(cursor.getColumnIndex("name"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
Toast.makeText(ListPage.this, img_url, Toast.LENGTH_SHORT).show();
grp = gridView.getFirstVisiblePosition();
Intent intent = new Intent(getApplicationContext(), Idolpiclist.class);
intent.putExtra("name", name);
startActivity(intent);
}
});
private class Myhand extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
cursor = (Cursor) msg.obj;
System.out.println(cursor.getCount());
GridView gridView = (GridView) findViewById(R.id.List_page_gridview);
gridView.setSelection(grp+1);
gridView.setAdapter(new Myadapter());
}
}
android.os.Process.setThreadPriority(-8);
android.os.Process.setThreadPriority(-8);
private class MyThread extends Thread {
@Override
public void run() {
android.os.Process.setThreadPriority(-8);
super.run();
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
Message message = myhand.obtainMessage();
message.obj = flickrSQL.SelectallIdol();
myhand.sendMessage(message);
}
}
private class MyThread extends Thread {
@Override
public void run() {
android.os.Process.setThreadPriority(-8);
super.run();
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
Message message = myhand.obtainMessage();
message.obj = flickrSQL.SelectallIdol();
myhand.sendMessage(message);
}
}
Android getDrawable,getColor 过时的替代方法
Android getDrawable,getColor 过时的替代方法
public class ContextCompat{}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
relativeLayout.addView(linearLayout);
for (int i = 0; i < 3; i++) {
ImageView imageView = new ImageView(this);
// 过时
// imageView.setImageDrawable(getDrawable(R.drawable.android));
// 替代方法
imageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.firefox));
TextView textView = new TextView(this);
textView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_orange_dark));
textView.setText(String.valueOf(i));
imageView.setId(i);
textView.setId(i);
linearLayout.addView(imageView);
linearLayout.addView(textView);
imageView.setOnClickListener(this);
textView.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
String idinfo = "";
switch (v.getId()) {
case 1:
idinfo = "Button1";
break;
case 2:
idinfo = "Button2";
break;
case 0:
idinfo = "Button1";
break;
}
Toast.makeText(this, idinfo, Toast.LENGTH_SHORT).show();
}
}
public class ContextCompat{}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
relativeLayout.addView(linearLayout);
for (int i = 0; i < 3; i++) {
ImageView imageView = new ImageView(this);
// 过时
// imageView.setImageDrawable(getDrawable(R.drawable.android));
// 替代方法
imageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.firefox));
TextView textView = new TextView(this);
textView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_orange_dark));
textView.setText(String.valueOf(i));
imageView.setId(i);
textView.setId(i);
linearLayout.addView(imageView);
linearLayout.addView(textView);
imageView.setOnClickListener(this);
textView.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
String idinfo = "";
switch (v.getId()) {
case 1:
idinfo = "Button1";
break;
case 2:
idinfo = "Button2";
break;
case 0:
idinfo = "Button1";
break;
}
Toast.makeText(this, idinfo, Toast.LENGTH_SHORT).show();
}
}
登録:
投稿 (Atom)