首页 > 代码库 > JAVA进阶-IO流(2)

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=http://www.mamicode.com/new LiveData();>
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等,只不过比较少用)

JAVA进阶-IO流(2)