学习IO流遇到的问题以及Junit单元测试报错问题

1.读写汉字文本文件

在进行写入操作时,如果写入的文件内含有汉字,则用以下代码

public class FISRead {
    public static void main(String[] args) throws IOException{
      	// 使用文件名称创建流对象.
       	FileInputStream fis = new FileInputStream("read.txt"); // read.txt文件中内容为abcde
      	// 定义变量,作为有效个数
        int len ;
        // 定义字节数组,作为装字节数据的容器   
        byte[] b = new byte[2];
        // 循环读取
        while (( len= fis.read(b))!=-1) {
           	// 每次读取后,把数组变成字符串打印
            System.out.println(new String(b));
        }
		// 关闭资源
        fis.close();
    }
}

输出结果:
ab
cd
ed

byte[] b=new byte[]内确定的空间即为每次读取的字节数,多了或者少了都会是汉字变成乱码,所以应该先测试该电脑该编码个=格式下的汉字占多少字节

public void test1() {
		String s="张";
		try {
			System.out.println(s.getBytes("UTF-8").clone().length);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

问题解决!

2.读写图片资源

先看图片的大小,如48.9KB,1KB=1024B,所以可以设置的稍微大一些

@Test
public void copypicture() {
	File f1=new File("D:\\q.jpg");
	File f2=new File("D:\\test\\copy.jpg");
	try {
		f2.createNewFile();
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	try {
		FileInputStream fin=new FileInputStream(f1);
		FileOutputStream fout=new FileOutputStream(f2);
		byte[] b=new byte[1024*50];//这个大小影响是否能传输成功,最好大一点
		int len=0;
		while((len=fin.read(b))!=-1) {
			fout.write(b,0,len);
			fout.flush();
		}
		fout.close();
		fin.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

在这里插入图片描述在这里插入图片描述在这里插入图片描述

Junit单元测试报错

在这里插入图片描述
在这里插入图片描述

package day5;

import org.junit.Test;

public class supermaket {
	final static String name="子伦超市";
	final static String address="大学生创业园";
	final static String phone="110";
	public void welcome() {
		System.out.println("物美超市欢迎你");
		System.out.println("超市名:"+name);
		System.out.println("超市地址:"+address);
		System.out.println("电话:"+phone);
	}
	public void discount(double price) {
		System.out.println("价格打85折:"+(price*0.85));
	}
	public static void main(String[] args) {
		supermaket s = new supermaket();
		s.discount(11);
		s.welcome();
	}
}

原因:测试的方法不能有返回值或者参数

3.FileOutputStream写入数据覆盖问题

实例化对象的时候添加true参数(默认为false,表示覆盖)

FileOutputStream fout=new FileOutputStream(f,true);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值