Java学习笔记二十三(IO流之FileInputStream和FileOutputStream)

FileInputStream和FileOutputStream类

这两个类中的read和write方法,都是每次读取以字节为单位的数据,括号中没有参数时,则只读取一个字节,读到文件末尾时,返回-1。

public class TestInputOutput {
	public static void main(String[] args) throws IOException {
		File file = new File("C:\\keshe\\test01.txt");
		if(!file.exists()) {
			file.createNewFile();
		}
	    InputStream in = new FileInputStream("C:\\keshe\\test01.txt");
	    OutputStream out = new FileOutputStream("C:\\keshe\\test01.txt");
	    out.write(65);
	    System.out.println(in.read());
	    out.close();
	    in.close();
	}
}

如果out.write()中括号内的数大于等于256的话,则不会存储大于256的部分(指的是数字在内存中是二进制存储的,而括号内的单位是字节,只能存储数的低8位,所以如果是260的话,低16位是00000001 00000100,只能存储00000100,即是4)。如果想存储大于256的话,可以采取下面的方法。

public class TestMAXINT {
	public static void main(String[] args) {
		Integer a = new Integer(Integer.MAX_VALUE);
		System.out.println(a);
		FileOutputStream file = null;
		FileInputStream file1 = null;
		try {
			file = new FileOutputStream("C:\\keshe\\f.txt");
			int b = a >> 8;
			int c = b >> 8;
			int d = c >> 8;
			file.write(d);
			file.write(c);
			file.write(b);
			file.write(a);
			file.close();
			file1 = new FileInputStream("C:\\keshe\\f.txt");
			int d1 = file1.read();
			int c1 = file1.read();
			int b1 = file1.read();
			int a1 = file1.read();
			int f = a1|(b1 << 8)|(c1 << 16 )|(d1 << 24);
			System.out.println(f);
			file1.close();
		}catch(Exception e) {
			e.getMessage();
		}
	}
}

在存储时对数据进行移位操作,每8位存储一次。读取时也是每次读取8位,再将当初移位的值移回去,再相加或者进行or操作即可产生原数。

一次读取多个字节的方法(使用带参数的read函数):

public class TestReadWrite {
	public static void main(String[] args) {
		FileInputStream file = null;
		try {
			file = new FileInputStream("C:\\keshe\\a.txt");
			byte[] bs = new byte[1024];
			/*
			 * int read(byte[] bs)
			 * 试着从文件中一次性读取bs.length个字节的数据,返回值是实际读取的字节数
			 * 读到的内容在bs数组里存放
			 */
			int len = file.read(bs);
			System.out.println(len);
			/*
			 * 将字节数组转换成字符串
			 */
			String str = new String(bs,0,len);
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(file != null) {
				try {
					file.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

上述代码的读部分还可以被简写成:

        byte[] bs = new byte[1024];
        int len = 0;
        while((len = file.read(bs))>0) {
                file1.write(bs,0,len);

         }

向文件中写入多个字节:

public class TestReadWrite2 {
		public static void main(String[] args) {
			FileOutputStream file = null;
			try {
				file = new FileOutputStream("C:\\keshe\\a.txt");
				String str = "shgs";
				file.write(str.getBytes());
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if(file != null) {
					try {
						file.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/weixin_40373090/article/details/82555882