JAVA学渣之路--IO篇三

2 篇文章 0 订阅
  1. 缓冲输入文件
    使用FileReader读取一个文件,然后在外层使用BufferedReader进行文件缓冲,这样子我们就可以缓冲输入的文件,由于是BufferedReader,所以提供了readLine()方法,所以,代码如下:
public class BufferedInputFile {
	public static String read(String filename) throws IOException {
		BufferedReader in = new BufferedReader(new FileReader(filename));
		String s;
		StringBuilder sb = new StringBuilder();
		while((s = in.readLine()) != null) {
			sb.append(s + "\n");
		}
		in.close();
		return sb.toString();
	}
	public static void main(String [] args) throws IOException {
		System.out.println(read("F:\\dist\\bundle.js"));
	}
}
  1. 从内存中输入
    从内存中读取,也就是说读取变量。这里提供了StringReader类,这个类可以每次读取一个字符。占两个字节。java中一个char类型变量占两个字节。
    代码如下:

    public static void main(String [] args) throws IOException {
    		StringReader in = new StringReader(BufferedInputFile.read("F:\\dist\\bundle.js"));
    		int c;
    		while((c = in.read()) != -1) {
    			System.out.print((char) c);
    		}
    	}
    

    但是这里需要注意的是read()方法返回的是int形式的,所以如果需要读成字符,需要将其转换为char类型。

  2. 格式化的内存输入
    由于需要格式化的数据,所以,这里使用面向字节的I/O类,所以开始使用InputStream而不是Reader类。使用DataInputStream类,这是个面向自己的InputStream类。
    代码如下:

    public class FormattedMemoryInput {
    	public static void main(String [] args) throws IOException {
    		try {
    			DataInputStream in = new DataInputStream(
    					new ByteArrayInputStream(
    							BufferedInputFile.read("F:\\dist\\bundle.js").getBytes()
    							)
    					);
    		}catch(EOFException e) {
    			System.err.println("End of Stream");
    		}
    	}
    }
    

    当然,这里必须要为DataInputSteam提供一个字符流,所以使用了ByteArrayInputStream类,而ByteArrayInputStream类,读取的是一个字符的数组对象。
    由于我们读取的字符都是char类型的,所以任何char类型的字符都是合法的,所以没有办法区分出什么时候是结尾,所以这时候 DataInputStream提供了一个方法available()方法,这个方法返回的是当前可供读取的字符数。
    代码如下:

    public class TestEOF {
    	public static void main(String [] args) throws IOException {
    		DataInputStream in = new DataInputStream(new BufferedInputStream(
    				new FileInputStream("F:\\dist\\bundle.js")));
    		while(in.available() != 0) {
    			System.out.print((char)in.readByte());
    		}
    	}
    }
    
  3. 基本的文件输出
    由于我们需要输出到文件,所以此时使用了FileWriter类,然后为了更高效率的输出,我们使用BufferedWriter作为缓冲写入,这里最后,为了输出的文件有格式,所以,这里使用了PrintWriter。所以最终代码如下:

public class BasicFileOutput {
	static String file = "BasicFileOutput.out";
	public static void main(String [] args) throws IOException {
		BufferedReader in = new BufferedReader(new StringReader("tessdfasfds\nasdfasfsa"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
		int lineCount = 1;
		String s;
		while((s = in.readLine()) != null) {
			out.println(lineCount++ + ": " + s);
		}
		out.flush();
		out.close();
		System.out.println(BufferedInputFile.read(file));
	}
}

当BufferedReader的readLine方法读取完时,将会返回null。这里最后需要为out显式的调用close()。如果不用close()的话,缓冲区的内容不会刷新清空,可能导致输出不完整。
其实大多数情况下,我们并不需要包装那么多层,我们只需要用PrintWriter类,往这个类传入file的名称即可,就可以实现上面我们内部封装的new BufferedWriter(new FileWriter(fileName));这里依旧会使用缓存,只是不必我们自己去实现了,代码如下:

static String file = "FileOutputShortcut.out";
	public static void main(String [] args) throws IOException {
		BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("F:\\dist\\bundle.js")));
		PrintWriter out = new PrintWriter(file);
		int lineCount = 1;
		String s;
		while((s = in.readLine()) != null) {
			out.println(lineCount++ + ": " + s);
		}
		out.close();
		System.out.println(BufferedInputFile.read(file));
	}
  1. 存储和恢复数据
    我们如果希望我们存储时按我们的想要的格式存储,读取时,还可以想要的格式读取,这时候就需要用到DataOutputStream, DataInputStream,这两个流可以保证我们写入文件和读取文件的时候以我们想要的格式写入和读取。代码如下
public class StoringAndRecoveringData {
	public static void main(String [] args) throws IOException {
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt")));
		out.writeDouble(3.14159);
		out.writeUTF("That was pi");
		out.writeDouble(1.41413);
		out.writeUTF("Square root of 2");
		out.close();
		DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("Data.txt")));
		System.out.println(in.readDouble());
		System.out.println(in.readUTF());
		System.out.println(in.readDouble());
		System.out.println(in.readUTF());
	}
}

当我们用DataOutputStream写入数据时,Java可以保证我们使用DataInputStream准确地读取数据。
6. 读写随机访问文件
这里随机访问文件,依靠RandomAccessFile类,并且可以使用seek()类,移动位置并修改指定位置的某个值。
代码如下:

public class UsingRandomAccessFile {
	static String file = "rtest.dat";
	static void display() throws IOException {
		RandomAccessFile rf = new RandomAccessFile(file, "r");
		for(int i = 0; i < 7; i++) {
			System.out.println("value " + i + ": " + rf.readDouble());
		}
		System.out.println(rf.readUTF());
		rf.close();
	}
	public static void main(String [] args) throws IOException {
		RandomAccessFile rf = new RandomAccessFile(file, "rw");
		for(int i = 0; i < 7; i++) {
			rf.writeDouble(i * 1.414);
		}
		rf.writeUTF("The end of the file");
		display();
		rf = new RandomAccessFile(file, "rw");
		rf.seek(5*8);
		rf.writeDouble(47.0001);
		rf.close();
		display();
	}
}
  1. 进程控制
    有时候,我们会想在java程序中运行其他程序,这时候就需要用到ProcessBuilder对象了,这个对象的底层是native的,也就是其他语言写的。java调用了这些native method。向ProcessBuilder传递一个参数,然后再调用start()方法,就会类似我们windows下的cmd命令行执行命令一样。代码如下:
	public static void command(String command) throws Exception {
		boolean err = false;
		try {
			// Process process = new ProcessBuilder(command.split(" ")).start();
			Process process = new ProcessBuilder(command.split(" ")).start();
			BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String s;
			while((s = results.readLine()) != null) {
				System.out.print(s);
			}
			BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			while((s = errors.readLine()) != null) {
				System.err.println(s);
				err = true;
			}
		} catch(Exception e) {
			System.out.println(e);
			if(!command.startsWith("CMD /C")) {
				command("CMD /C" + command);
			}else {
				throw new RuntimeException(e);
			}
		}
		if(err) {
			throw new OSExecuteException("Errors executing " + command);
		}
	}

这里多了一点读取这个Process返回标准输出流,使用Process.getInputStream()捕获。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值