inputstreamreader类是用于将_readstring

inputstreamreader类是用于将_readstring一、InputStreamReader类InputStreamReader将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。构造方法:InputStreamReaderisr=newInputStreamReader(InputStreamin);//构造一个默认编码集的InputStr

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

inputstreamreader类是用于将_readstring


一、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!

inputstreamreader类是用于将_readstring

上次的代码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账号...

(0)
blank

相关推荐

  • 利用 SSDP 协议生成 100 Gbps DDoS 流量的真相探秘「建议收藏」

    利用 SSDP 协议生成 100 Gbps DDoS 流量的真相探秘「建议收藏」原文地址https://www.4hou.com/technology/5979.html上个月我们分享过一些反射型DDoS攻击数据,SSDP攻击的平均大小是12Gbps,我们记录的最大的反射式DDoS攻击是:1.30Mpps(每秒数百万个数据包)2.80Gbps(每秒数十亿位)3.使用940k反射器的IP几天前,我们注意到了一个不寻常的SSDP超级放大情况的发生…

    2022年10月10日
  • 计算机病毒的分类

    计算机病毒的分类病毒与木马病毒:指编制或在计算机程序中插入的破坏计算机功能或破坏数据,影响计算机使用并且能够自我复制的一组计算机指令或程序代码。木马:是一种后门程序,被黑客用作控制远程计算机的工具。木马与病毒不同的是,木马不会自我繁殖,并不会刻意地感染其他文件,它的作用就是为黑客打开远程计算机的门户,从而可以让黑客来远程控制计算机,使黑客获取有用的信息。病毒是自动破坏目标计算机,而木马需要人为的去操控…

  • TinEye Reverse Search Engine_tidb和mysql

    TinEye Reverse Search Engine_tidb和mysqlCUSTOMER表CREATETABLE`CUSTOMER`(`C_CUSTKEY`intNOTNULL,`C_NAME`varcharNOTNULL,`C_ADDRESS`varcharNOTNULL,`C_NATIONKEY`intNOTNULL,`C_PHONE`varcharNOTNULL,`C_ACCTBAL`decimal(12,2)NOT…

  • pytest重试_pytest的conftest

    pytest重试_pytest的conftest安装:pip3installpytest-rerunfailures重新运行所有失败用例要重新运行所有测试失败的用例,请使用–reruns命令行选项,并指定要运行测试的最大次数:$py

  • Python常用模块 之 hashlib模块——简单实现实现登录注册

    Python常用模块 之 hashlib模块——简单实现实现登录注册(唯一要求:使用hashlib中的md5进行加密!)importhashlibimportredefdenglu():user1=input(‘请输入你的账号:’)pwd=input(‘请输入你的密码:’)count=0withopen(‘json1.txt’,’r’)asf:foriinf:user,passwd=i.split(‘|’)resu

  • kafuka 的安装以及基本使用

    kafuka 的安装以及基本使用最近因为项目需要所以需要使用kafka所以自己最近也实践了下。下面为大家简单介绍下在windows下的安装使用因为它是基于zookepper的使用也要安装zookepper1.安装ZookeeperKafka的运行依赖于Zookeeper,所以在运行Kafka之前我们需要安装并运行Zookeeper1.1下载安装文件:http://mirror.bit.edu.cn/apache…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号