读文件

method 1

package com.oop;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
	public static void main(String[] args) throws FileNotFoundException {
		File file = new File("c://hello.txt");
		
		if(!file.exists()) {
			throw new FileNotFoundException(file.getName()+"isn't found!");
		}
		
		String line;
		
		try {
			FileReader fileReader = new FileReader(file);
			BufferedReader br = new BufferedReader(fileReader);
			line = br.readLine();
			
			while(line != null) {
				System.out.println(line);
				line = br.readLine();
			}
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

method 2

package com.oop;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadFile2 {
	public static void main(String[] args) throws IOException {
		File file = new File("c://hello.txt");
		if (!file.exists()) {
			System.out.println(file.getName()+"isn't exists!");
		}
		
		FileInputStream fs = new FileInputStream(file);
		FileOutputStream out = new FileOutputStream("c://hello2.txt");
		byte[] b = new byte[1024]; 
		int len;
		while((len=fs.read(b)) != -1) {
			fs.read(b);
			out.write(b);
		}
		
		try {
			out.close();
			fs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

method 3

package com.oop;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFile {
	public static void main(String[] args) throws IOException {
		File file = new File("c://hello.txt");
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		FileInputStream fs = new FileInputStream(file);
		byte[] b = new byte[5]; 
		int input;
		while((input=fs.read(b)) != -1) {
			String s = new String(b, 0, input);
			System.out.println(s);
		}
		
		try {
			fs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
posted @ 2022-05-30 09:15  wjxuriel  阅读(37)  评论(0)    收藏  举报