java文件操作--Thinking in java

   文件操作应该是JAVA最基础但是也是最重要的一部分了,下面奉上几个简单的例子

  

package com.bird.thinking;

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * @use  缓冲读取文件
 * @author Bird
 *
 */
public class BufferedInputFile {
	public static String read(String FileName) throws Exception{
		BufferedReader in = new BufferedReader(new FileReader(FileName));//设立缓冲区
		String s = null;
		StringBuilder sb = new StringBuilder();//尽量使用StringBuilder,迅速
		while((s = in.readLine()) != null){
			sb.append(s + "\n");
		}
		in.close();
		return sb.toString();
	}
	
	public static void main(String [] args) throws Exception{
		System.out.println(read("d://book.xml"));
	}
}



package com.bird.thinking;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StringReader;

/**
 * @use 基本写文件操作
 * @author Bird
 *
 */
public class BasicFileOutput {
	public static String file = "d://egg.java";
	public static void main(String [] args) throws Exception{
		BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("d://book.xml")));//构建输入对象
	//	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));//构建输出对象
		PrintWriter out = new PrintWriter(file);//快捷方式写法,仍然使用缓冲区
		String s = null;
		while((s = in.readLine()) != null){
			out.write(s);
		}
		out.close();//一定要关闭刷新缓冲区,否则文件不完整
		in.close();
		
		
	}
}



package com.bird.thinking;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @use 使用Data写入读取数据,无论读写平台的不同
 * @author Bird
 *
 */
public class StoringAndRecoveringData {
	@SuppressWarnings("deprecation")
	public static void main(String [] args) throws Exception{
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("d://egg.xml")));
		out.writeDouble(3.1415926);//使用二进制写入文件
		out.writeUTF("Fall in Love");
		out.writeInt(5);
		out.close();
		Thread.sleep(500);//避免磁盘未写入完毕
		
		DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("d://egg.xml")));
		while(in.available() != 0){
			System.out.println(in.readLine());
		}
	}
}


阅读更多
个人分类: JAVA
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭