基于字节的I/O操作
基于字符的I/O操作
读写文件:字节流,字符流,整行读等
操作文件:以模拟复制文件,罗列根目录下所有文件的例子说明常用文件操作
控制台输入输出:普通输入输出和快速输入输出
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.Reader; import java.io.Writer; import java.util.Scanner; public class FileTest { public static void main(String[] args) throws IOException { String fileName = "D:/test.txt"; String newFileName = "D:/testCopy.txt"; String root = "D:\\Web\\新建文件夹"; // readFileByBytes(fileName); // readFileByChars(fileName); // readFileByLines(fileName); // readFileByRandomAccess(fileName); // appendByRandomAccessFile(fileName, "abcde"); // appendByFileWrite(fileName, "我"); // writeFileByChars(fileName, "你好"); // writeFileByBytes(fileName, "111"); // copyFile(fileName, newFileName); // listFileAndFolder(root); consoleInputAndOutput(); } /** * 以子节为单位读取文件,常用于读二进制文件,如图片,声音等文件 * * @param fileName * 文件名 */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; byte[] data = new byte[(int) file.length()]; int len = 0; try { System.out.println("以子节为单位读取文件内容,一次读一个字节"); in = new FileInputStream(file); int read; while ((read = in.read()) != -1) { data[len++] = (byte) read; // 单个输出,非汉字正确输出.转换成字符输出 System.out.write(read); } String result = new String(data, 0, len); // 非汉字时正常输出 System.out.println("result:" + result); } catch (IOException e) { e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 字符流读文件 * * @param fileName * 文件名 */ public static void readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; try { // 设置编码,可以读取汉字 reader = new InputStreamReader(new FileInputStream(file), "GBK"); int read; byte[] data = new byte[(int) file.length()]; int len = 0; while ((read = reader.read()) != -1) { data[len++] = (byte) read; // 对于windows,\r\n两个字符表示一个换行 // 分开显示时换行两次 if ((char) read != '\r') { System.out.println((char) read); } } } catch (Exception e) { e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 整行读取文件 * * @param fileName * 文件名 */ public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("读一整行:"); // 读取非汉字可用 // reader = new BufferedReader(new FileReader(file)); // 读汉字可用 reader = new BufferedReader(new InputStreamReader( new FileInputStream(file), "GBK")); String str; int line = 0; while (null != (str = reader.readLine())) { System.out.println("line " + line + ": " + str); line++; } } catch (IOException e) { e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 随机读取文件 * * @param fileName * 文件名称 */ public static void readFileByRandomAccess(String fileName) { RandomAccessFile randomFile = null; try { System.out.println("随机读取文件:"); // r为只读,w为只写,rw读写 randomFile = new RandomAccessFile(fileName, "r"); // 设置读取位置 randomFile.seek(0); // 读取到的数据 byte[] bytes = new byte[10]; int len = 0; // 读取数据,非汉字 while ((len = randomFile.read(bytes)) != -1) { System.out.write(bytes, 0, len); } // 文件指针位置 System.out.println(randomFile.getFilePointer()); } catch (IOException e) { e.printStackTrace(); } finally { if (null != randomFile) { try { randomFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 在文件末尾追加数据 * * @param fileName * 文件名 * @param content * 追加的数据 */ public static void appendByRandomAccessFile(String fileName, String content) { RandomAccessFile randomFile = null; try { // 以读写方式打开 randomFile = new RandomAccessFile(fileName, "rw"); // 获取文件长度 long len = randomFile.length(); // 移动文件指针到文件末 randomFile.seek(len); randomFile.writeBytes(content); } catch (IOException e) { e.printStackTrace(); } finally { if (null != randomFile) { try { randomFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("randomAccessFile追加操作完成"); } /** * 已FileWrite方式追加文本 * * @param fileName * 文件名 * @param content * 追加内容 */ public static void appendByFileWrite(String fileName, String content) { FileWriter writer = null; try { // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != writer) { try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("FileWriter追加操作完成"); } /** * 字符写文件 * * @param fileName * 文件名 * @param content * 写入内容 */ public static void writeFileByChars(String fileName, String content) { File file = new File(fileName); Writer writer = null; try { // 设置编码,可以写汉字 writer = new OutputStreamWriter(new FileOutputStream(file), "GBK"); // 写入数据 writer.append(content); } catch (Exception e) { e.printStackTrace(); } finally { if (null != writer) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("字符流写入操作完成"); } /** * 已字节流写内容到文件 * * @param fileName * 文件名 * @param content * 写入内容 */ public static void writeFileByBytes(String fileName, String content) { File file = new File(fileName); OutputStream out = null; try { System.out.println("以子节为单位写文件"); out = new FileOutputStream(file); byte[] bytes = content.getBytes(); out.write(bytes, 0, bytes.length); } catch (IOException e) { e.printStackTrace(); } finally { if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("字节流写入操作完成"); } /** * 拷贝文件,包括文本文件,图片等 * * @param fileName * 待拷贝文件 * @param newFileName * 拷贝结果文件 */ public static void copyFile(String fileName, String newFileName) { System.out.println("文件拷贝开始 。。。。。。。。。"); File file = new File(fileName); File newFile = new File(newFileName); if (!file.exists()) { System.out.println("待拷贝文件不存在"); return; } // 拷贝结果文件已存在,就删除 if (newFile.exists()) { newFile.delete(); } // 创建新的拷贝结果文件 try { newFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 字节流 InputStream in = null; OutputStream out = null; try { in = new FileInputStream(file); out = new FileOutputStream(newFile); byte[] data = new byte[(int) file.length()]; int len = 0; int read = -1; System.out.println("文件大小:" + file.length()); // 读取数据 while ((read = in.read()) != -1) { data[len++] = (byte) read; } // 写入数据 out.write(data); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("文件拷贝结束 。。。。。。。。。"); } /** * 罗列根目录下所有文件和文件夹,dfs * * @param root * 根目录 */ public static void listFileAndFolder(String root) { File file = new File(root); if (!file.exists()) { System.out.println("跟目录不存在"); return; } // 是文件 if (file.isFile()) { System.out.println("文件名:" + file.getName() + ",文件路径:" + file.getAbsolutePath() + ",文件大小:" + file.length()); return; } // 是文件夹 if (file.isDirectory()) { System.out.println("文件夹名:" + file.getName() + ",文件夹路径:" + file.getAbsolutePath() + ",文件夹大小:" + file.length()); // 获取文件夹下所有文件和文件夹对象 File[] files = file.listFiles(); // 获取文件夹下所有文件和文件夹名称 String[] list = file.list(); System.out.print(file.getName() + "文件夹下包含:"); if (null != list) { for (int i = 0; i < list.length; i++) { if (i == 0) { System.out.print(list[i]); } else { System.out.println("," + list[i]); } } System.out.println(); } for (int i = 0; i < files.length; i++) { listFileAndFolder(files[i].getAbsolutePath()); } } } /** * 控制台上输入和输出 --分普通输入输出和快速输入输出 --快速输入输出是为acm竞赛这样的追求效率的使用,普通情况下普通输入输出就够了 */ public static void consoleInputAndOutput() { // 普通输出定义 Scanner cin = new Scanner(System.in); // 快速输入定义 Reader reader = new InputStreamReader(System.in); Writer writer = new OutputStreamWriter(System.out); try { // 普通输入输出 Integer num = cin.nextInt(); System.out.println(num); // 快速输入输出 int read = getInt(reader);// 调用函数输入数字 // 输出数字的时候,write会将数字转换成字符,即输出97的时候会输出a;所以需要转换成字符串 writer.write(Integer.toString(read)); writer.flush();// 强制将内存中的数据输出到控制台上 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null != writer) { try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null != cin) { cin.close(); } } } /** * 获取键盘输入的整数 * * @return 输入的整数 */ public static int getInt(Reader reader) { int read; int res = 0; boolean isNegative = false;// 是不是负数 try { while ((read = reader.read()) != -1) { if ((char) read == '-') { res = 0; isNegative = true; break; } else if (isNumber((char) read)) { res = read - '0'; break; } } while ((read = reader.read()) != -1) { char ch = (char) read; if (isNumber(ch)) { res = res * 10 + (read - '0'); } else { break; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (isNegative == true) { res = -1 * res; } return res; } /** * 判断字符是不是数字 * * @param ch * 字符 * @return 判断结果 */ public static boolean isNumber(char ch) { if (ch <= '9' && ch >= '0') { return true; } return false; } }
发表评论(对文章涉及的知识点还有疑问,可以在这里留言,老高看到后会及时回复的。)