码迷,mamicode.com
首页 > 编程语言 > 详细

Java操作IO各主要类介绍

时间:2014-05-06 21:12:07      阅读:567      评论:0      收藏:0      [点我收藏+]

标签:java   io   dataoutputstream   bytearrayoutputstrea   fileoutputstream   

DataInputStream和DataOutputStream

往二进制文件中读和写入java基本数据类型

public class BinaryReadWrite {
	private DataInputStream dis = null;
	private DataOutputStream dos = null;
	private String s_FilePath = "config\\bin.dat";
	private byte[] buff = "{\"name\":\"alen\"}".getBytes();

	public BinaryReadWrite() 
	{
		init();
	}

	private void init() 
	{
		try 
		{
			if (!new File(s_FilePath).exists()) 
			{
				new File(s_FilePath).createNewFile();
			}
			dos = new DataOutputStream(new FileOutputStream(new File(s_FilePath)));
			dis = new DataInputStream(new FileInputStream(new File(s_FilePath)));
		} catch (Exception e) 
		{
			e.printStackTrace();
		}
	}

	public void writeBinaryStream() throws IOException 
	{
		if (dos != null) 
		{
			dos.writeBoolean(true);
			
			char c = ‘a‘;
			dos.writeChar((int) c);
			
			Double d = 12.567d;
			dos.writeDouble(d);
			
			Float f = 56.782f;
			dos.writeFloat(f);
			
			int k = 105;
			dos.writeInt(k);
			
			long l = 98765l;
			dos.writeLong(l);
			
			short st = 12;
			dos.writeShort(st);
			
			String cs = "Java读写二进制文件";
			dos.writeUTF(cs);
			dos.writeInt(buff.length);
			dos.write(buff, 0, buff.length);
			
			dos.flush();
			dos.close();
		}
	}

	public void readBinaryStream() throws IOException {
		if (dis != null) {
			while (dis.available() > 0) {
				System.out.println(dis.available());
				System.out.println(dis.readBoolean());
				System.out.println((char) dis.readChar());
				System.out.println(dis.readDouble());
				System.out.println(dis.readFloat());
				System.out.println(dis.readInt());
				System.out.println(dis.readLong());
				System.out.println(dis.readShort());
				System.out.println(dis.readUTF());
				int len = dis.readInt();
				byte[] buffer = new byte[len];
				dis.read(buffer, 0, buffer.length);
				String data = new String(buffer,"UTF-8");
				System.out.println(data);
			}
		}
	}

	public static void main(String[] args) throws IOException {
		BinaryReadWrite bin = new BinaryReadWrite();
		bin.writeBinaryStream();
		bin.readBinaryStream();
	}
}

ByteArrayInputStream

字节数组输入流,把字节串(或叫字节数组)变成输入流的形式,可以依次读取每个字节

public class ByteArrayInputStreamTest
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		try
		{
			byte[] buff = new byte[] { 0, 1, 2,127,-1,-2, -128,‘0‘,‘1‘,‘2‘,‘3‘,‘a‘,‘b‘,‘A‘,‘B‘};

			InputStream in = new ByteArrayInputStream(buff, 0, buff.length);
			int data = 0;
			while ((data=  in.read()) != -1)
			{
				System.out.println(data + " ");
			}
			in.close();

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
打印结果:




127 
255 
254 
128 
48 
49 
50 
51 
97 
98 
65 
66
 

FileInputStream

文件输入流,从文件系统中的某个文件中获得输入字节

public class FileInputStreamTest {

	public static void main(String[] args) {
		try {
			/*String fileName = "D:"+File.separator+"hello.txt";*/
			String fileName ="config/build.xml";
			File f = new File(fileName);

			InputStream in = new FileInputStream(f);

			byte[] b = new byte[(int)f.length()];

			int len = in.read(b);
			//或者一个一个读
			/*
			for (int i = 0; i < b.length; i++) 
			{
	            b[i]=(byte)in.read();
	        }
	        System.out.println(new String(b));
	        */

			in.close();

			System.out.println("读入长度为:"+len);

			System.out.println(new String(b,0,len));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

遍历文件夹

public class FileList {

	public static void main(String[] args) {
		/*File file = new File("E:/STUDY");*/
		File file = new File("config");
		String[] names = file.list();
		for(String data:names)
		{
			System.out.println(data);
		}
		
		File[] f = file.listFiles();
		for(File data:f)
		{
			System.out.println(data.getName());
		}
	}
}


读取网络上的图片并转换成字节数组输出流,再将其转换为字节数组

public class ReadNetImage
{
	public byte[] getImageUrl(String imageUrl)
	{
		byte[] fileData = null;
		try
		{
			URL url = new URL(imageUrl);  
			
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();  
			
			httpConn.connect();  
			
			InputStream is = httpConn.getInputStream();  
			
			ByteArrayOutputStream bos = new ByteArrayOutputStream();  
			
			byte[] buffer = new byte[400];  
			
			int len = 0;  
			
			while ((len = is.read(buffer,0,400)) != -1) 
			{  
			    bos.write(buffer, 0, len);  
			}  
			
			fileData = bos.toByteArray();  
			
			is.close(); 
			bos.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
        return fileData;
	}
}

BufferedOutputStream

该类实现缓冲的输出流。通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统。 

public class TestBufferedOutputStream
{
	public static void main(String[] args) throws Exception
	{
		OutputStream os = new FileOutputStream("config/test.txt");
		
		BufferedOutputStream  bos = new BufferedOutputStream(os);
		
		bos.write("http://google.com/".getBytes());
		
		bos.close();
		os.close();
	}
}

ByteArrayOutputStream

此类实现了一个输出流,其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray()toString() 获取数据。 

public class TestByteArrayOutputStream {

	public static void main(String[] args) throws Exception {
		ByteArrayOutputStream bos= new ByteArrayOutputStream();
		
		//知道byte数组,往ByteArrayOutputStream组织数据
		byte[] buffer = "hello world".getBytes();
		/*
		 * ByteArrayOutputStream输出流的write方法只是把byte数组组织进去
		 * 不会往硬盘执行写
		 */
		bos.write(buffer);
		
		//可以把ByteArrayOutputStream输出流变成byte数组
		byte[] result =bos.toByteArray();

		for (int i = 0; i < result.length; i++) 
		{
			System.out.println((char) result[i]);
		}
		
		//A
		OutputStream os = new FileOutputStream("config/test.txt");
		bos.writeTo(os);
		
		//B
		os.write(result);//知道byte数组数据      往硬盘写入数据 没必要再转一次
		
		//C包装一个管道缓冲区
		BufferedOutputStream buffos = new BufferedOutputStream(os);
		buffos.write(result);

		bos.close();
		os.close();
		buffos.close();

	}

	/**
	 * 根据指定目录文件
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytesFromFile(String filePath, String fileName) 
	{
		byte[] buffer = null;
		try 
		{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			
			InputStream is = new FileInputStream(new File(filePath , fileName));
			
			byte[] b = new byte[1000];
			
			int len = 0;;
			
			/*
			 * 读取FileInputStream的输入流到ByteArrayOutputStream中
			 * 是为了得到byte数组
			 */
			while ((len = is.read(b,0,1000)) != -1) 
			{
				/*
				 * ByteArrayOutputStream的write方法只是把byte数组组织进去
				 * 不会往硬盘执行写
				 */
				bos.write(b, 0, len);
			}
			
			buffer = bos.toByteArray();
			
			is.close();
			
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return buffer;
	}
}

FileOutputStream

文件输出流是用于将数据写入 FileFileDescriptor 的输出流。文件是否可用或能否可以被创建取决于基础平台。

FileOutputStream 用于写入诸如图像数据之类的原始字节的流。要写入字符流,请考虑使用 FileWriter

public class TestFileOutputStream {
	/**
	 * 知道某个byte数组
	 * 往指定的目录生成文件
	 */
	public  void getFileFromBytes(byte[] bfile, String filePath, String fileName) 
	{
		try {
			File dir = new File(filePath);
			// 判断文件目录是否存在
			if (!dir.exists()) 
			{
				dir.mkdirs();
			}
			
			OutputStream os = new FileOutputStream(new File(filePath , fileName));
			
			BufferedOutputStream bos = new BufferedOutputStream(os);
			
			bos.write(bfile);
			
			bos.close();
			
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 知道指定的目录文件
	 * 从中读书byte数据
	 * 并且往另一目录文件写入相同的文件
	 */
	public  void getFileFromFile(String filePath, String fileName)
	{
		try
		{
			OutputStream os = new FileOutputStream(new File("config\\","test.txt"));
			BufferedOutputStream  bos = new BufferedOutputStream(os);
			
			InputStream is = new FileInputStream(new File(filePath , fileName));
			
			byte[] buffer = new byte[200];
			
			int len = 0;
			/*
			 * 从FileInputStream输入流中不断的读取byte数组
			 * 并且往被BufferedOutputStream包装的缓冲区写硬盘
			 */
			while((len = is.read(buffer)) > 0)
			{
				bos.write(buffer,0,len);
				System.out.println(new String(buffer,0,len));
			}
			/*
			byte[] b = new byte[(int)new File(filePath , fileName).length()];

		    int count = 0;

		    int temp = 0;

		    while((temp = is.read())!=(-1))
		    {
		          b[count++] = (byte)temp;
		          System.out.println((char)temp);
		    }
		    System.out.println(new String(b));
		    os.write(b);
			*/
			
			/*
			byte[] b = new byte[(int)new File(filePath , fileName).length()];

		    for (int i = 0; i < b.length; i++) 
			{
	            b[i] = (byte)is.read();
	            System.out.println((char)b[i]);
	        }
		    System.out.println(new String(b));
		    os.write(b);
			*/
			
			is.close();
			bos.close();
			os.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws IOException
	{
		TestFileOutputStream test = new TestFileOutputStream();
		test.getFileFromFile("config", "user.xml");
	}
}

FileReader

用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。

public class TestFileReader {

	public static void main(String[] args) {
		FileReader fr=null;
		int c=0;
		try {
			fr=new FileReader("config/user.xml");
			while((c=fr.read())!=-1){
				System.out.print((char)c);
			}
			fr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
}

FileWriter

用来写入字符文件的便捷类

public class TestFileWriter {

	public static void main(String[] args) {
		FileWriter fw=null;
		try {
			fw =new FileWriter("config/filewriter.txt");
			fw.write("hello");
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		System.out.println("写入正常");
	}
}

以上都是日常开发中,我们所常用的IO类,基本满足我们的开发需求。

Java操作IO各主要类介绍,布布扣,bubuko.com

Java操作IO各主要类介绍

标签:java   io   dataoutputstream   bytearrayoutputstrea   fileoutputstream   

原文地址:http://blog.csdn.net/lovesomnus/article/details/25097507

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!