FileUtils.java代碼:
public class FileUtils {
private String SDPATH;
public String getSDPATH() {
return SDPATH;
}
public FileUtils() {
// 得到當前外部存盤設備的目錄
// /SDCARD
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在SD卡上創建檔案
*
* @throws IOException
*/
public File creatSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 在SD卡上創建目錄
*
* @param dirName
*/
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdirs();
return dir;
}
/**
* 判斷SD卡上的檔案夾是否存在
*/
public boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 將一個InputStream里面的資料寫入到SD卡中
*/
public File write2SDFromInput(String path, String fileName,
InputStream input) {
File file = null;
OutputStream output = null;
try {
creatSDDir(path);
file = creatSDFile(path + fileName);
output = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while ((input.read(buffer)) != -1) {
output.write(buffer);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
}
HttpDownloader.java代碼:
public class HttpDownloader {
private URL url = null;
/**
* 根據URL下載檔案,前提是這個檔案當中的內容是文本,函式的回傳值就是檔案當中的內容 1.創建一個URL物件
* 2.通過URL物件,創建一個HttpURLConnection物件 3.得到InputStram 4.從InputStream當中讀取資料
*
* @param urlStr
* @return
*/
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
// 創建一個URL物件
System.out.println("執行0");
url = new URL(urlStr);
// 創建一個Http連接
System.out.println("執行1");
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 使用IO流讀取資料
System.out.println("執行2");
buffer = new BufferedReader(new InputStreamReader( //空指標
urlConn.getInputStream()));
System.out.println("執行3");
while ((line = buffer.readLine()) != null) {
System.out.println("執行4");
sb.append(line);
}
} catch (Exception e) {
System.out.println("download:" + e.getMessage());
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
System.out.println("download buffer.close():" + e.getMessage());
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 該函式回傳整形 -1:代表下載檔案出錯 0:代表下載檔案成功 1:代表檔案已經存在
*/
public int downFile(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();
if (fileUtils.isFileExist(path + fileName)) {
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName,
inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
System.out.println("downFile:" + e.getMessage());
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
System.out.println("downFile close:" + e.getMessage());
e.printStackTrace();
}
}
return 0;
}
/**
* 根據URL得到輸入流
*
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConn.getInputStream();
return inputStream;
}
}
MainActivity.java 代碼:
public class MainActivity extends Activity {
private Button downloadTxtButton;
private Button downloadMp3Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadTxtButton=(Button)findViewById(R.id.downloadTxtButton);
downloadMp3Button=(Button)findViewById(R.id.downloadMp3Button);
downloadTxtButton.setOnClickListener(new DownloadTxtListener());
downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}*/
}
class DownloadTxtListener implements OnClickListener{
@Override
public void onClick(View v) {
System.out.println("txt");
HttpDownloader httpDownloader=new HttpDownloader();
String lrc=httpDownloader.download("http://10.0.2.2:8080/myWebTest/book1.txt");
System.out.println("lrc="+lrc);
}
}
class DownloadMp3Listener implements OnClickListener{
@Override
public void onClick(View v) {
HttpDownloader httpDownloader=new HttpDownloader();
int ret=httpDownloader.downFile("http://10.0.2.2:8080/myWebTest/book1.txt","books/","book2.txt");
System.out.println("ret="+ret);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
已知報一個 android.os.NetworkOnMainThreadException 和空指標的錯,
buffer = new BufferedReader(new InputStreamReader( //空指標
urlConn.getInputStream()));
求指點!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/150955.html
標籤:網絡通信
上一篇:Python實作掃碼工具
