java基础(流,读控制台数据,读取和复制文件)

概述

java.io包几乎包含了所有操作输入,输出需要的类。
程序中输入输出都是以流的形式保存的,流中保存的都是字节文件。

读取控制台输入

BufferedReader br = new BufferedReader(new InputStreamReader(System.in))

下面程序示范了从控制台读取字符方法read(),直到用户输入q

import java.io.*;
public class BRead {
   
	public static void main(String args[]) throw IOException {
   
		char c;
		BufferReader br = new BufferReader(new InputStreamReader(System.in));
		System.out.print("输入字符,按下q退出");
		do{
   
			c=(char)br.read();//监控控制台输入的数
			System.out.println(c);//在控制台打印出
		}while(c!='q');
	}
}

下面展示了从控制台读取字符串使用readLine(),下面程序显示字符串直到你输入了end。

import java.io.*;

public class Stream2 {
   

	public static void main(String[] args) throws IOException{
   
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str;
		System.out.println("Enter");
		System.out.println("End Widt quit");
		do {
   
			str = br.readLine();//str等于控制台读到的数
			System.out.println(str);
		}while(str!="end");
	}
}

读取写入文件

在java.io包中提供了专用于文件输入输出功能的包
InputStream和OutputStream是为字节流设计的,主要用来处理字节。
Reader和Writer是为字符流设计的,主要用来处理字符或字符串。

字符流处理的单元为2个字节的Unicode字符,分别操作字符,字符数组或字符串。而字节流处理单元为1个字节,操作字节和字节数组。

字节流

字节流操作写文件

栗子1public class OutpubStream01 {
   
	public static void main(String[] args) throws IOException{
   
		File f = new File("E:"+File.separator+"test.txt");
		OutputStream out = new FileOutputStream(f);
		String str = "hello word";
		byte[] b = str.getBytes();//把str存到b中
		out.write(b);//调用写入流out对象,把b写入
		out.close();
	}
}
栗子2:一个一个字节写入
public class OutputStream02 {
   
	public static void main(String[] args) throws IOException {
   
		File f = new File("E:"+File.separator
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值