大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
一、InputStreamReader类
InputStreamReader 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。
构造方法:
InputStreamReader isr = new InputStreamReader(InputStream in);//构造一个默认编码集的InputStreamReader类
InputStreamReader isr = new InputStreamReader(InputStream in,String charsetName);//构造一个指定编码集的InputStreamReader类。参数 in对象通过 InputStream in = System.in;获得。//读取键盘上的数据。 或者 InputStream in = new FileInputStream(String fileName);//读取文件中的数据。可以看出FileInputStream 为InputStream的子类。
主要方法:int read();//读取单个字符。 int read(char []cbuf);//将读取到的字符存到数组中。返回读取的字符数。
(注意这里是手机的路径)
package com.example.pc.httpconnectiontest;import android.os.Environment;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * Created by pc on 2016/4/19. */public class InputStreamReaderTest { public static String transReadNoBuf() throws IOException { /** * 没有缓冲区,只能使用read()方法。 */ //读取字节流// InputStream in = System.in;//读取键盘的输入。 String extr = Environment.getExternalStorageDirectory().getPath(); File mFolder = new File(extr +"//"+ "demo.txt"); if (!mFolder.exists()) { mFolder.mkdir(); } InputStream in = new FileInputStream(mFolder);//读取文件的数据。 //将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节. InputStreamReader isr = new InputStreamReader(in,"UTF-8");//读取 char []cha = new char[1024]; int len = isr.read(cha); System.out.println(new String(cha, 0, len)); String str = new String(cha, 0, len); isr.close(); in.close(); return str; } public static String transReadByBuf() throws IOException { /** * 使用缓冲区 可以使用缓冲区对象的 read() 和 readLine()方法。 */ //读取字节流// InputStream in = System.in;//读取键盘上的数据 String extr = Environment.getExternalStorageDirectory().toString(); File mFolder = new File(extr +"//"+ "demo.txt"); if (!mFolder.exists()) { mFolder.mkdir(); } InputStream in = new FileInputStream(mFolder);//读取文件的数据。 //将字节流向字符流的转换。 InputStreamReader isr = new InputStreamReader(in);//读取 //创建字符流缓冲区 BufferedReader bufr = new BufferedReader(isr);//缓冲 String line = null; while((line = bufr.readLine())!=null){ System.out.println(line); } bufr.close(); isr.close(); in.close(); return line; }}
二、OutputStreamWriter类
OutputStreamWriter 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。
构造方法:
OutputStreamWriter osw = new OutputStreamWriter(OutputStream out);//构造一个默认编码集的OutputStreamWriter类
OutputStreamWriter osw = new OutputStreamWriter(OutputStream out,String charsetName);//构造一个指定编码集的OutputStreamWriter类。参数 out对象通过 InputStream out = System.out;获得。//打印到控制台上。或者 InputStream out = new FileoutputStream(String fileName);//输出到文件中。可以看出FileoutputStream 为outputStream的子类。
主要方法:void write(int c);//将单个字符写入。
viod write(String str,int off,int len);//将字符串某部分写入。
void flush();//将该流中的缓冲数据刷到目的地中去。
(注意这里是针对电脑D盘的路径,用手机操做就要写手机的路径)
public static void transWriteNoBuf() throws IOException { OutputStream out = System.out;//打印到控制台 // OutputStream out = new FileOutputStream(new File("D:\\demo.txt"));//打印到文件 OutputStreamWriter osr = new OutputStreamWriter(out);//输出 // OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream("D:\\demo.txt"));//两句可以综合到一句。 // int ch = 97;//a // int ch = 20320;//你 // osr.write(ch); String str = "你好吗?";//你好吗? osr.write(str); osr.flush(); osr.close(); } public static void transWriteByBuf() throws IOException { // OutputStream out = System.out;//打印到控制台。 OutputStream out = new FileOutputStream("D:\\demo.txt");//打印到文件。 OutputStreamWriter osr = new OutputStreamWriter(out);//输出 // OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream("D:\\demo.txt"));//综合到一句。 BufferedWriter bufw = new BufferedWriter(osr);//缓冲 // int ch = 97;//a // int ch = 20320;//你 // osr.write(ch); String str = "你好吗?\r\n我很好!";//你好吗? bufw.write(str); bufw.flush(); bufw.close(); }
MainActivity
package com.example.pc.httpconnectiontest;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast;import java.io.IOException;public class MainActivity extends AppCompatActivity { private String content; private String str_noBuf; private String str_Buf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); Button button2 = (Button) findViewById(R.id.button2); Button button3 = (Button) findViewById(R.id.button3); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { //网络Connection请求方面 content = HttpConnectionUtil.getHttpContent("http://www.baidu.com"); if (content != null && content != "") { Message message = mhandler.obtainMessage(); message.what = 1; message.obj = ""; mhandler.sendMessage(message); } } }).start(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { //InputStreamReaderTest nobuf try { str_noBuf = InputStreamReaderTest.transReadNoBuf(); Log.d("MainActivity","str_noBuf?"); } catch (IOException e) { e.printStackTrace(); } if (str_noBuf != null && str_noBuf != "") { Message message = mhandler.obtainMessage(); message.what = 2; mhandler.sendMessage(message); } Log.d("MainActivity","str_noBuf=="+str_noBuf); } }).start(); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { //InputStreamReaderTest nobuf try { str_Buf = InputStreamReaderTest.transReadNoBuf(); } catch (IOException e) { e.printStackTrace(); } if (str_Buf != null && str_Buf != "") { Message message = mhandler.obtainMessage(); message.what = 3; mhandler.sendMessage(message); } } }).start(); } }); } private Handler mhandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: Toast.makeText(MainActivity.this, content, Toast.LENGTH_LONG).show(); Log.d("MainActivity", content); break; case 2: Toast.makeText(MainActivity.this, str_noBuf, Toast.LENGTH_LONG).show(); Log.d("MainActivity", str_noBuf); break; case 3: Toast.makeText(MainActivity.this, str_Buf, Toast.LENGTH_LONG).show(); Log.d("MainActivity", str_Buf); break; default: break; } } };}
布局文件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Button1" android:id="@+id/button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Button2" android:id="@+id/button2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Button3" android:id="@+id/button3" /></LinearLayout>
mainifest文件
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.pc.httpconnectiontest" > <uses-permission android:name="android.permission.INTERNET"/> <!--往sdcard中写入数据的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <!--在sdcard中创建/删除文件的权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></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" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
在写这段代码时候用于测试电脑D盘目录的java文件
package com.example.pc.httpconnectiontest;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;/** * Created by pc on 2016/4/19. */public class FileTest { public static void main(String [] arges ) throws IOException { /* String content = HttpConnectionUtil.getHttpContent("http://www.baidu.com"); System.out.print("content =="+content);*/ String content =""; /* File file = new File("D:\\demo.txt"); InputStream is = new FileInputStream(file) ;*/ InputStream is = new FileInputStream(new File("D:\\demo.txt"));//读取文件的数据。 InputStreamReader isr = new InputStreamReader(is,"UTF-8"); BufferedReader br = new BufferedReader(isr); String line = ""; while((line=br.readLine()) !=null){ content+= line; } System.out.println(content); if(br!=null){ br.close(); }else if (isr!=null){ isr.close(); }else if (is!=null){ is.close(); } }}
demo.txt文件,随便写了几个hello world!
上次的代码HttpConnection
package com.example.pc.httpconnectiontest;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by pc on 2016/4/18. * <p/> * 工具类 */public class HttpConnectionUtil { public static String getHttpContent(String url) { return getHttpContent(url, "UTF-8"); } private static String getHttpContent(String url, String charSet) { HttpURLConnection connection = null; String content = ""; try { URL address_url = new URL(url); connection = (HttpURLConnection) address_url.openConnection(); connection.setRequestMethod("GET"); //设置访问超时时间及读取网页流的超市时间,毫秒值 connection.setConnectTimeout(1000); connection.setReadTimeout(1000); //得到访问页面的返回值 int response_code = connection.getResponseCode(); if(response_code== HttpURLConnection.HTTP_OK){ InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,charSet)); //把字节流读取出来 String line = ""; while((line = bufferedReader.readLine()) !=null){ content+= line; } return content; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (connection!=null){ connection.disconnect(); } } return ""; } /*public static void main(String [] arges ){ String content = HttpConnectionUtil.getHttpContent("http://www.baidu.com"); System.out.print("content =="+content); }*/}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/189268.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...