按字节读取读取文件,并且将文件里面的内容写到另外一个文件里面去
- public class CopyBytes {
- public static void main(String[] args) throws IOException {
- FileInputStream in = null;
- FileOutputStream out = null;
- try {
- in = new FileInputStream("xanadu.txt");
- out = new FileOutputStream("outagain.txt");
- int c;
- while ((c = in.read()) != -1) {
- out.write(c);
- }
- } finally {
- if (in != null) {
- in.close();
- }
- if (out != null) {
- out.close();
- }
- }
- }
- }
------------------------------------------------------------------------
缓冲存储
- public class CopyCharacters {
- public static void main(String[] args) throws IOException {
- FileReader inputStream = null;
- FileWriter outputStream = null;
- try {
- inputStream = new FileReader("xanadu.txt");
- outputStream = new FileWriter("characteroutput.txt");
- int c;
- while ((c = inputStream.read()) != -1) {
- outputStream.write(c);
- }
- } finally {
- if (inputStream != null) {
- inputStream.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- }
- }
- }
------------------------------------------------------------------------------------
按行读取
- public class CopyLines {
- public static void main(String[] args) throws IOException {
- BufferedReader inputStream = null;
- PrintWriter outputStream = null;
- try {
- inputStream =
- new BufferedReader(new FileReader("xanadu.txt"));
- outputStream =
- new PrintWriter(new FileWriter("characteroutput.txt"));
- String l;
- while ((l = inputStream.readLine()) != null) {
- outputStream.println(l);
- }
- } finally {
- if (inputStream != null) {
- inputStream.close();
- }
- if (outputStream != null) {
- outputStream.close();
- }
- }
- }
- }
----------------------------------------------------------------------------
直接读取文件内容
- public class ScanXan {
- public static void main(String[] args) throws FileNotFoundException {
- Scanner s = null;
- try {
- s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
- while (s.hasNext()) {
- System.out.println(s.next());
- }
- } finally {
- if (s != null) {
- s.close();
- }
- }
- }
- }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/751843