JAVA进阶-IO流(2)

<2>以下介绍一些7.0中比较高级的io流.

5.DirectoryStream根据给定路径列举当前文件

1)Files.newDirectoryStream(path,".*");第2个参数指定搜索的文件格式

/**
 *		列举目录/文件
 *
 * 	@author Lean  @date:2014-9-22
 */
public class DirListing {

	public static void main(String[] args) {
		listDir("E:\\zftphoneTv");
	}

	public static void listDir(String fileDir){

		Path path=Paths.get(fileDir);
		DirectoryStream<Path> dirctoryStream=null;
		try {
			dirctoryStream=Files.newDirectoryStream(path,".*");
			for (Path p : dirctoryStream) {
				System.out.println(p.getParent()+"\\"+p.getFileName());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (dirctoryStream!=null) {
				try {
					dirctoryStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

6.合并文件

1)通过BufferedWriter循环写入

/**
 *		级联合并文件
 *
 * 	@author Lean  @date:2014-9-22
 */
public class LeveFileSample {

	public static void main(String[] args) {
		String infilePath1 = "C:/Users/Administrator/Desktop/aa.txt";
		String inFilePath2 = "C:/Users/Administrator/Desktop/bb.txt";
		String outFilePath = "C:/Users/Administrator/Desktop/cc.txt";
		concenateFile(outFilePath, infilePath1,inFilePath2);
	}

	public static void concenateFile(String outFilePath,String... filePaths){
		BufferedWriter bufferedWriter=null;
		try {
			bufferedWriter=new BufferedWriter(new FileWriter(new File(outFilePath)));
			for (String filePath : filePaths) {
				FileReader reader=null;
				try {
					reader=new FileReader(new File(filePath));
					int readNum=0;
					char[] buff=new char[128];
					while ((readNum=reader.read(buff))!=-1) {
						bufferedWriter.write(buff,0,readNum);
					}
					bufferedWriter.newLine();
					buff=new char[128];
				} catch (IOException e) {
				}finally{
					if (reader!=null) {
						reader.close();
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if (bufferedWriter!=null) {
					bufferedWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}

2)SequenceInputStream,通过枚举循环并入流中.如下:将合并的流写入新文件

/**
 *		合并流
 *
 * 	@author Lean  @date:2014-9-23
 */
public class FileMerge {

	public Vector<String> fileNames=new Vector<String>();
	public Vector<InputStream> fileStreams=new Vector<InputStream>();

	public static void main(String[] args) {
		FileMerge fileMerge=new FileMerge();
		fileMerge.getFileNames();
		try {
			if (fileMerge.getFileStream()) {
				fileMerge.mergeFiles();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void mergeFiles() {
		String outFilePath="C:/Users/Administrator/Desktop/kk.txt";
		OutputStream outputStream=null;
		byte[] buff=new byte[512];
		int readNum=0;
		try {
			outputStream=new FileOutputStream(outFilePath);
			SequenceInputStream sequenceInputStream=new SequenceInputStream(fileStreams.elements());
			while ((readNum=(sequenceInputStream.read(buff)))!=-1) {
				outputStream.write(buff,0,readNum);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (outputStream!=null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private boolean getFileStream() throws FileNotFoundException {
		if (fileNames.size()<1)
			return false;
		for (String fileName : fileNames) {
			fileStreams.add(new FileInputStream(fileName));
		}
		return true;
	}

	public void getFileNames(){
		String aFile="C:/Users/Administrator/Desktop/a.txt";
		String bFile="C:/Users/Administrator/Desktop/b.txt";
		String cFile="C:/Users/Administrator/Desktop/c.txt";
		fileNames.add(aFile);
		fileNames.add(bFile);
		fileNames.add(cFile);
	}

}

7.ByteArrayOutputStream/DataOutputStream与ByteArrayInputStream/DataInputStream相互对应,data为byte的装饰器.一般应用在对象转换成字节数组传输的情况下,被传输的对象不需要继承任何接口.

/**
 *		字节流/数组 应用
 *
 * 	@author Lean  @date:2014-9-23
 */
public class LiveData {

	private ByteArrayOutputStream outputStream;

	public static void main(String[] args) {
		LiveData data=new LiveData();
		data.createData();
		data.readData();
	}

	public void createData(){
		try {
			outputStream=new ByteArrayOutputStream();
			DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
			for (int i = 0; i <20; i++) {
				Trade trade=new Trade(i);
				dataOutputStream.writeInt(trade.scripCode);
				dataOutputStream.write(trade.time);
				dataOutputStream.writeDouble(trade.bid);
				dataOutputStream.writeDouble(trade.offer);
				dataOutputStream.writeDouble(trade.high);
				dataOutputStream.writeDouble(trade.low);
				dataOutputStream.writeLong(trade.quantity);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void readData(){
		byte[] timeBuff=new byte[8];
		ByteArrayInputStream inputStream=new ByteArrayInputStream(outputStream.toByteArray());
		DataInputStream dataInputStream=new DataInputStream(inputStream);
		try {
			for (int i = 0; i < 20; i++) {
				int scripCode=dataInputStream.readInt();
				dataInputStream.read(timeBuff);
				String time=new String(timeBuff);
				double bid=dataInputStream.readDouble();
				double offer=dataInputStream.readDouble();
				double high=dataInputStream.readDouble();
				double low=dataInputStream.readDouble();
				long quantity=dataInputStream.readLong();
				System.out.println("scripCode>"+scripCode+" time>"+time+" bid>"+bid+" offer>"+offer+" high>"+high+" low>"+low+" quantity>"+quantity+" ");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

8.有的时候,我们需要计算文档的字数,或对文档的控制转换成对文档内容的控制(控制/查询文字/数字).JAVA为我们提供了StreamTokenizer.该类可以将文件流转换成一个个的指令,相当于指针控制内存.

/**
 *		文字/数字 解析
 *
 * 	@author Lean  @date:2014-9-23
 */
public class WordAndNumberParser {

	public static void main(String[] args) {

		WordAndNumberParser parser=new WordAndNumberParser();
		parser.parseFile("C:/Users/Administrator/Desktop/kk.txt");

	}

	public void parseFile(String fileName){
		int wordCount=0;
		int numberCount=0;
		try (FileReader reader=new FileReader(fileName);){
			StreamTokenizer tokenizer=new StreamTokenizer(reader);
			tokenizer.slashSlashComments(true);
			tokenizer.slashStarComments(true);
			while (tokenizer.nextToken()!=StreamTokenizer.TT_EOF) {
				if (tokenizer.ttype==StreamTokenizer.TT_WORD) {
					wordCount++;
				}else if (tokenizer.ttype==StreamTokenizer.TT_NUMBER) {
					numberCount++;
				}
				if (tokenizer.sval!=null&&tokenizer.sval.equals("a")) {
					System.out.println(tokenizer.toString());
				}

			}
			System.out.println("wordCount:"+wordCount +"  numberCount:"+numberCount);

		} catch (Exception e) {
			System.out.println("error parser");
		}

	}

}

9.RandomAccessFile同样也是对文件的操作,只不过它是对字节的操作.seek()方法跳过非法的内容.其一般应用在多线程下载/断点下载.以下为断点下载的例子:

/**
 *
 *
 * 	@author Lean  @date:2014-9-23
 */
public class RecordFile {

	public static int fileLength(String urlPath){
		HttpURLConnection connection=null;
		int length=0;
		try {
			URL url=new URL(urlPath);
			connection=(HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(5000);
			if (connection.getResponseCode()==200) {
				length=connection.getContentLength();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return length;
	}

	public static long downFileLength(String downPath){
		File file=new File(downPath);
		return file.length();
	}

}
/**
 *
 *
 * 	@author Lean  @date:2014-9-23
 */
public class BreakPointDownLoad extends Thread{

	private String downLoadPath;
	private String urlPath;

	public BreakPointDownLoad(String downLoadPath,String urlPath) {
		this.downLoadPath=downLoadPath;
		this.urlPath=urlPath;
	}

	@Override
	public void run() {
		RandomAccessFile raf=null;
		InputStream fis=null;
		HttpURLConnection conn=null;
		try {
			int allFileLength=RecordFile.fileLength(urlPath);
			long currDownLength=RecordFile.downFileLength(downLoadPath);
			long startIndex=currDownLength!=0?currDownLength+1:currDownLength;
			System.out.println(allFileLength+"   "+currDownLength);
			conn=(HttpURLConnection) new URL(urlPath).openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			//request header note!
			conn.setRequestProperty("Range", "bytes="+startIndex+"-"+allFileLength);
			if (conn.getResponseCode()==206) {
				raf=new RandomAccessFile(downLoadPath,"rwd");
				raf.seek(startIndex);
				fis=conn.getInputStream();
				byte[] buff=new byte[512];
				int readNum=0;
				while ((readNum=(fis.read(buff)))!=-1) {
					raf.write(buff,0,readNum);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
				try {
					if (raf!=null) {
						raf.close();
					}
					if (fis!=null) {
						fis.close();
					}
					conn.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

}

(高级部分还有如PrintStream,LineNumberInputStream,PushbackInputStream等,只不过比较少用)

时间: 2025-01-14 12:41:32

JAVA进阶-IO流(2)的相关文章

java进阶 ------ IO流

[本文是自己学习所做笔记,欢迎转载,但请注明出处:http://blog.csdn.net/jesson20121020] 流的概念和基本分类: 流的概念: 流是一个很形象的概念,当程序需要读取数据的时候,就会开启一个通向数据的源的流,这个数据源可以是文件,内存,或是网络连接.类似的,当程序需要写入数据的时候,就会开启一个通向目的地的流.这时候你就可以想象数据好像在这其中"流动一样". 流的分类: 按数据方向分:输入流和输出流 输入流:InputStream/Reader 输出流:Ou

JAVA进阶-IO流(1)

http://download.csdn.net/detail/qq285016127/7963747 Java对文件的操作API一般分为字节流 字符流 其为文件的读写API框架也是通过这个思想去扩展的.另外,在流的流向中也分为源流和宿流.如图(流的主体是根据流向决定,如输入InputStream/输出流OutPutStream) <1>从整个框架上看,io流的主要知识点分为: 1.字节流(输入FileInputStream/输出FileOutputStream) 1)字节流的构造一般都会通过

java常用IO流数据流小结

  类名 常用方法 说明 输入流 InputStream int read(); 只能读字节流,虽然返回值是int,但只有低8位起作用. DataInputStream Type readType(); 可以读二进制流,可以读byte,short,int,long,double等二进制流. BufferedReader String readLine(); 可以读文本行. 输出流 OutputStream void write(int); 只能写字节流,虽然形参是int,但只有低8为起作用. D

【Java】IO流简单分辨

转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5827509.html Java的IO流体系十分庞大,并且体系层次稍复杂,很容易记混或记错.在此,我把平时经常用到的几个流类的简易区分以及体系层次整理出来,方便记忆与辨析.本人对IO了解尚浅,文章如有错漏,恳请前辈指正,感激不尽! 字节流体系: 基类:InputStream/outputStream(抽象类,不能new) 子类: 文件IO字节流:FileInputStream/FileoutputStream

JAVA中IO流总结

本文是在学习中的总结,欢迎转载但请注明出处:http://write.blog.csdn.net/postedit/42119261 我想你对JAVA的IO流有所了解,平时使用的也比较的多,但是对于其具体分类和继承体系可能知道的并不多,可能也很少去看相关的API文档,找出其中的关系和各自的应用情形.本文简单对常用的IO流进行分类整理,并简单举例说明其应用.希望本文对你有所帮助. (A)IO流大致分为两种: (1)字节流:对应抽象类为InputStream(输入流)和 OutputStream(输

【JAVA的 IO流之FileInputStream和FileOutputStream】

java的 IO流即输入输出流,流是一组有顺序的,有起点和终点的字节结合,是对数据传输的总称.即数据在两设备间的传输称为流,流的本质是数据传输. IO流可以分为字节流和字符流.给出相应的IO结构图: 在接下来的一段时间里,将会慢慢介绍各种流的使用,本篇博客先介绍字节流的FileOutputStream和相对应的FileInputStream. 一.FileOutputStream(文件输出流) OutputStream是一个抽象类,抽象类必须通过子类实现.现在要向文件里输出就要用FileOutp

java的IO流,字节流和字符流

java操作文件都是通过流来处理的,(其实其他很多语言也是这样) 第一:java的IO流,分为:输入流 和 输出流(这真是废话,这是从流向的角度来说的) 第二:java的所有IO流,只分为:字节流 和 字符流(其实就是传输的颗粒,传输的基本单位) 总结:凡是处理纯文本的优先考虑字符流:其他的才考虑使用字节流

Java之IO流---字节流

1.1 IO流的引入 IO流在很多语言已有体现,诸如C语言的stdio.h,C++中的iostream.Java中的IO流大抵是用于在控制台.磁盘.内存上进行数据的读写操作,完成数据的传递. 我们可以对它进行如下分类: 按处理的数据类型可分为字节流与字符流 按流的流向可分为输入流(in)与输出流(out) 按流的功能可分为节点流(Node)和过滤流(Filter) 本篇侧重于梳理字节流相关的知识,毕竟作为字符流的前辈,它还是非常重要的.下篇继续梳理字符流. 1.2 IO流的继承体系图 大概描述了

Java笔记-IO流的运用

1.InputStream和System.in(Scanner) InputStream 输出流以字节为单位来获取数据,且需要复杂的判断并创建字节数组作为缓冲 另外字节转换为字符时容易出现中文乱码的情况:Scanner Java扫描器类,可以从输入流中读取指定类型的数据或字符串. 对于字符数据的读取,应该使用Scanner扫描器进行封装,然后获取字符串类型的数据 2. out和err out和err是System类的两个static类成员变量: out:主要是输出调试信息的输出流,以黑色显示 e