java中多种方式读文件,追加文件内容,对文件的各种操作
一、多种方式读文件内容。
1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容
2008-5-7 09:48 我思念的城市
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * @param fileName 文件的名
*/
public static void readFileByBytes(String fileName){
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while((tempbyte=in.read()) != -1){
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
//一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
//读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1){
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null){
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
* @param fileName 文件名
*/
2008-5-7 09:52 我思念的城市
public static void readFileByChars(String fileName){
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1){
//对于windows下,\r\n这两个字符在一起时,表示一个换行。
//但如果这两个字符分开显示时,会换两次行。
//因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char)tempchar) != '\r'){
System.out.print((char)tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
//一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
//读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars))!=-1){
//同样屏蔽掉\r不显示
if ((charread ==
tempchars.length)&&(tempchars[tempchars.length-1] != '\r')){ System.out.print(tempchars);
}else{
for (int i=0; i if(tempchars[i] == '\r'){ continue; }else{ System.out.print(tempchars[i]); } } } } } catch (Exception e1) { e1.printStackTrace(); }finally { if (reader != null){ try { reader.close(); } catch (IOException e1) { } } } } /** * 以行为单位读取文件,常用于读面向行的格式化文件 * @param fileName 文件名 */ 2008-5-7 09:53 我思念的城市 public static void readFileByLines(String fileName){ File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; //一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null){ //显示行号 System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null){ try { reader.close(); } catch (IOException e1) { } } } } /** * 随机读取文件内容 * @param fileName 文件名 */ 2008-5-7 09:55 我思念的城市 public static void readFileByRandomAccess(String fileName){ RandomAccessFile randomFile = null; try { System.out.println("随机读取一段文件内容:"); // 打开一个随机访问文件流,按只读方式 randomFile = new RandomAccessFile(fileName, "r"); // 文件长度,字节数 long fileLength = randomFile.length(); // 读文件的起始位置 int beginIndex = (fileLength > 4) ? 4 : 0; //将读文件的开始位置移到beginIndex位置。 randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。 //将一次读取的字节数赋给byteread while ((byteread = randomFile.read(bytes)) != -1){ System.out.write(bytes, 0, byteread); } } catch (IOException e){ e.printStackTrace(); } finally { if (randomFile != null){ try { randomFile.close(); } catch (IOException e1) { } } } } /** * 显示输入流中还剩的字节数 * @param in */ 2008-5-7 09:55 我思念的城市 private static void showAvailableBytes(InputStream in){ try { System.out.println("当前字节输入流中的字节数为:" + in.available()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; ReadFromFile.readFileByBytes(fileName); ReadFromFile.readFileByChars(fileName); ReadFromFile.readFileByLines(fileName); ReadFromFile.readFileByRandomAccess(fileName); } } 2008-5-7 09:56 我思念的城市 二、将内容追加到文件尾部 import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; /** * 将内容追加到文件尾部 */ public class AppendToFile { /** * A方法追加文件:使用RandomAccessFile * @param fileName 文件名 * @param content 追加的内容 */ public static void appendMethodA(String fileName, String content){ try { // 打开一个随机访问文件流,按读写方式 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); //将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(content); randomFile.close(); } catch (IOException e){ e.printStackTrace(); } } /** * B方法追加文件:使用FileWriter * @param fileName * @param content */ public static void appendMethodB(String fileName, String content){ try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } 2008-5-7 09:57 我思念的城市 三文件的各种操作类 import java.io.*; /** * FileOperate.java * 文件的各种操作 * @author 杨彩[url]https://www.doczj.com/doc/796164593.html,/m/yangcai[/url] * 文件操作1.0 */ public class FileOperate { public FileOperate() { } /** * 新建目录 */ public void newFolder(String folderPath) { try { String filePath = folderPath; filePath = filePath.toString(); File myFilePath = new File(filePath); if(!myFilePath.exists()) { myFilePath.mkdir(); } System.out.println("新建目录操作成功执行"); } catch(Exception e) { System.out.println("新建目录操作出错"); e.printStackTrace(); } } /** * 新建文件 */ 2008-5-7 09:58 我思念的城市 public void newFile(String filePathAndName, String fileContent) { try { String filePath = filePathAndName; filePath = filePath.toString(); File myFilePath = new File(filePath); if (!myFilePath.exists()) { myFilePath.createNewFile(); } FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); String strContent = fileContent; myFile.println(strContent); resultFile.close(); System.out.println("新建文件操作成功执行"); } catch (Exception e) { System.out.println("新建目录操作出错"); e.printStackTrace(); } } /** * 删除文件 */ 2008-5-7 09:58 我思念的城市 public void delFile(String filePathAndName) { try { String filePath = filePathAndName; filePath = filePath.toString(); File myDelFile = new File(filePath); myDelFile.delete(); System.out.println("删除文件操作成功执行"); } catch (Exception e) { System.out.println("删除文件操作出错"); e.printStackTrace(); } } /** * 删除文件夹 */ public void delFolder(String folderPath) { try { delAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); File myFilePath = new File(filePath); if(myFilePath.delete()) { //删除空文件夹 System.out.println("删除文件夹" + folderPath + "操作成功执行"); } else { System.out.println("删除文件夹" + folderPath + "操作执行失败"); } } catch (Exception e) { System.out.println("删除文件夹操作出错"); e.printStackTrace(); } } /** * 删除文件夹里面的所有文件 * @param path String 文件夹路径如c:/fqf */ 2008-5-7 09:59 我思念的城市 public void delAllFile(String path) { File file = new File(path); if(!file.exists()) { return; } if(!file.isDirectory()) { return; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if(path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { //delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件 delFolder(path+ File.separatorChar + tempList[i]);//再删除空文件夹 } } System.out.println("删除文件操作成功执行"); } /** * 复制单个文件 * @param oldPath String 原文件路径如:c:/fqf.txt * @param newPath String 复制后路径如:f:/fqf.txt */ 2008-5-7 09:59 我思念的城市 public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldPath); //读入原文件 FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } System.out.println("删除文件夹操作成功执行"); } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } /** * 复制整个文件夹内容 * @param oldPath String 原文件路径如:c:/fqf * @param newPath String 复制后路径如:f:/fqf/ff */ 2008-5-7 10:00 我思念的城市 public void copyFolder(String oldPath, String newPath) { { (new File(newPath)).mkdirs(); //如果文件夹不存在则建立新文件夹 File a=new File(oldPath); String[] file=a.list(); File temp=null; for (int i = 0; i < file.length; i++) { if(oldPath.endsWith(File.separator)) { temp=new File(oldPath+file[i]); } else { temp=new File(oldPath+File.separator+file[i]); } if(temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString()); byte[] b = new byte[1024 * 5]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()) { //如果是子文件夹 copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); } } System.out.println("复制文件夹操作成功执行"); } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } /** * 移动文件到指定目录 * @param oldPath String 如:c:/fqf.txt * @param newPath String 如:d:/fqf.txt */ 2008-5-7 10:01 我思念的城市 public static void main(String args[]) { String aa,bb; boolean exitnow=false; System.out.println("使用此功能请按[1] 功能一:新建目录"); System.out.println("使用此功能请按[2] 功能二:新建文件"); System.out.println("使用此功能请按[3] 功能三:删除文件"); System.out.println("使用此功能请按[4] 功能四:删除文件夹"); System.out.println("使用此功能请按[5] 功能五:删除文件夹里面的所有文件"); System.out.println("使用此功能请按[6] 功能六:复制文件"); System.out.println("使用此功能请按[7] 功能七:复制文件夹的所有内容"); System.out.println("使用此功能请按[8] 功能八:移动文件到指定目录"); System.out.println("使用此功能请按[9] 功能九:移动文件夹到指定目录"); System.out.println("使用此功能请按[10] 退出程序"); while(!exitnow) { FileOperate fo=new FileOperate(); try { BufferedReader Bin=new BufferedReader(new InputStreamReader(System.in)); String a=Bin.readLine(); int b=Integer.parseInt(a); switch(b) { case 1:System.out.println("你选择了功能一请输入目录名"); aa=Bin.readLine(); fo.newFolder(aa); break; case 2:System.out.println("你选择了功能二请输入文件名"); aa=Bin.readLine(); System.out.println("请输入在"+aa+"中的内容"); bb=Bin.readLine(); fo.newFile(aa,bb); break; case 3:System.out.println("你选择了功能三请输入文件名"); aa=Bin.readLine(); fo.delFile(aa); break; case 4:System.out.println("你选择了功能四请输入文件名"); aa=Bin.readLine(); fo.delFolder(aa); break; case 5:System.out.println("你选择了功能五请输入文件名"); aa=Bin.readLine(); fo.delAllFile(aa); break; case 6:System.out.println("你选择了功能六请输入文件名"); aa=Bin.readLine(); System.out.println("请输入目标文件名"); bb=Bin.readLine(); fo.copyFile(aa,bb); break; case 7:System.out.println("你选择了功能七请输入源文件名"); aa=Bin.readLine(); System.out.println("请输入目标文件名"); bb=Bin.readLine(); fo.copyFolder(aa,bb); break; case 8:System.out.println("你选择了功能八请输入源文件名"); aa=Bin.readLine(); System.out.println("请输入目标文件名"); bb=Bin.readLine(); fo.moveFile(aa,bb); break; case 9:System.out.println("你选择了功能九请输入源文件名"); aa=Bin.readLine(); System.out.println("请输入目标文件名"); bb=Bin.readLine(); fo.moveFolder(aa,bb); break; case 10:exitnow=true; System.out.println("程序结束,请退出"); break; default:System.out.println("输入错误.请输入1-10之间的数"); } System.out.println("请重新选择功能"); } catch(Exception e) { System.out.println("输入错误字符或程序出错"); } } } } java 文件流操作 2010-05-08 20:17:23| 分类:java SE | 标签:|字号大中小订阅 java中多种方式读文件 一、多种方式读文件内容。 1、按字节读取文件内容InputStream 读取的是字节 2、按字符读取文件内容InputStreamReader 读取的是字符 3、按行读取文件内容BufferredReader 可以读取行 4、随机读取文件内容 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。* @param fileName 文件的名 */ public static void readFileByBytes(String fileName){ File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while((tempbyte=in.read()) != -1){ System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); //一次读多个字节 java创建txt文件并进行读写修改操作 import java.io.*;/** * * 功能描述:创建TXT文件并进行读、写、修改操作* */ public class ReadWriteFile { public static BufferedReader bufread; //指定文件路径和名称 private static String path = "D:/suncity.txt"; private static File filename = new File(path); private static String readStr =""; /** * 创建文本文件. * @throws IOException * */ public static void creatTxtFile() throws IOException{ if (!filename.exists()) { filename.createNewFile(); System.err.println(filename + "已创建!"); } } /** * 读取文本文件. * */ public static String readTxtFile(){ String read; FileReader fileread; try { fileread = new FileReader(filename); bufread = new BufferedReader(fileread); try { while ((read = bufread.readLine()) != null) { readStr = readStr + read+ "\r\n"; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block 获取文本内容与读取文本指定行数内容浅析(java) 在此项目中直接套用以前工程中获取文本内容的方法发现一直提示“数组下标越界”,通过分析和查找得出以下心得: 获取文本内容: private static final String CHART_PATH ="D://data3"; public static void main(String[] args) throws RowsExceededException,WriteException, BiffException{ try { readFileByLines(CHART_PATH+".txt"); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } public static void readFileByLines(String fileName) throws IOException,RowsExceededException,WriteException{ //打开文件 WritableWorkbook book = Workbook.createWorkbook( new File(CHART_PATH+".xls")); WritableSheet sheet = book.createSheet("看我", 0); //读取txt文件内容 File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis,"GBK"); BufferedReader reader = null; try { reader = new BufferedReader(isr); String temString = null; //一次读入一行,以null结束 int i = 0; while((temString = reader.readLine())!= null){ System.out.println("+++++++"+temString); String[] str = temString.split(","); for(int j= 0;j java对文件名的几个操作,获取文件扩展名,去掉扩展名 /** * Return the extension portion of the file's name . * * @see #getExtension */ public static String getExtension(File f) { return (f != null) ? getExtension(f.getName()) : ""; } public static String getExtension(String filename) { return getExtension(filename, ""); } public static String getExtension(String filename) { return getExtension(filename, ""); } public static String getExtension(String filename, String defExt) { if ((filename != null) && (filename.length() > 0)) { int i = https://www.doczj.com/doc/796164593.html,stIndexOf('.'); if ((i >-1) && (i < (filename.length() - 1))) { return filename.substring(i + 1); } } return defExt; } public static String trimExtension(String filename) { if ((filename != null) && (filename.length() > 0)) { int i = https://www.doczj.com/doc/796164593.html,stIndexOf('.'); if ((i >-1) && (i < (filename.length()))) { return filename.substring(0, i); } } return filename; } substring(参数)是java中截取字符串的一个方法 有两种传参方式 I/O类体系 在JDK API中,基础的IO类都位于java.io包,而新实现的IO类则位于一系列以java.nio开头的包名中,这里首先介绍java.io包中类的体系结构。 按照前面的说明,流是有方向的,则整个流的结构按照流的方向可以划分为两类: 1、输入流: 该类流将外部数据源的数据转换为流,程序通过读取该类流中的数据,完成对于外部数据源中数据的读入。 2、输出流: 该类流完成将流中的数据转换到对应的数据源中,程序通过向该类流中写入数据,完成将数据写入到对应的外部数据源中。 而在实际实现时,由于JDK API历史的原因,在java.io包中又实现了两类流:字节流(byte stream)和字符流(char stream)。这两种流实现的是流中数据序列的单位,在字节流中,数据序列以byte为单位,也就是流中的数据按照一个byte一个byte的顺序实现成流,对于该类流操作的基本单位是一个byte,而对于字节流,数据序列以char为单位,也就是流中的数据按照一个char一个插入的顺序实现成流,对于该类流操作的基本单位是一个char。 另外字节流是从JDK1.0开始加入到API中的,而字符流则是从JDK1.1开始才加入到API中的,对于现在使用的JDK版本来说,这两类流都包含在API的内部。在实际使用时,字符流的效率要比字节流高一些。 在实际使用时,字符流中的类基本上和字节流中的类对应,所以在开始学习IO类时,可以从最基础的字节流开始学习。 在SUN设计JDK的IO类时,按照以上的分类,为每个系列的类设计了一个父类,而实现具体操作的类都作为该系列类的子类,则IO类设计时的四个体系中每个体系中对应的父类分别是: 字节输入流InputStream 该类是IO编程中所有字节输入流的父类,熟悉该类的使用将对使用字节输入流产生很大的帮助,下面做一下详细的介绍。 按照前面介绍的流的概念,字节输入流完成的是按照字节形式构造读取数据的输入流的结构,每个该类的对象就是一个实际的输入流,在构造时由API完成将外部数据源转换为流对象的操作,这种转换对程序员来说是透明的。在程序使用时,程序员只需要读取该流对象,就可以完成对于外部数据的读取了。 Java 读取上传文件里的数据,记事本文件和excel文件 本文,文本文件里的数据,每列以 Tab 分隔。 其它分隔符情况下,只需修改对分隔符的判断即可 本文是将文本文件或excel文件里的数据读到List Java读取Excel文件的几种方法 最近单位有个项目需要读取excel文件的内容,特别对java读取excel文件的方法做了一点学习,也为了其他人以后能更简单地开发,少走弯路,特写此文,以下程序经过了我的测试,可以保证程序可用,如果你照搬都不行,可能是你的环境有问题。 读取excel文件的常用开源免费方法有以下几种: JDBC-ODBC Excel Driver jxl.jar jcom.jar poi.jar 下面分别对这几种方法分别进行探讨 1、JDBC-ODBC Excel Driver 这种方法是将excel看成是数据库进行操作,使用SQL Select语句即可 查询excel表格。优点是:不需要第三方的jar包。 如下表样 首先在控制面板进行数据源ODBC登记 具体方法如下: 下面就是代码了。 package xuzhe; import java.io.*; import java.sql.*; //java xuzhe.ExcelJDBC public class ExcelJDBC { public static void main(String[] args) throws SQLException{ Connection con = null; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection( "jdbc:odbc:ExcelJDBC" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" ); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); System.out.println ("表格列数"+numberOfColumns ); System.out.println( rsmd.getColumnName(1)+ "," + rsmd.getColumnName(2) + "," + rsmd.getColumnName(3)); while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) System.out.print(", "); String columnValue = rs.getString(i); System.out.print(columnValue); } System.out.println(""); } rs.close(); st.close(); } catch(Exception ex) { System.err.print("Exception: "); System.err.println(ex.getMessage()); } finally { con.close(); } } } 执行结果如下: 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); // 一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); ReadFromFile.showAvailableBytes(in); // 读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1) { System.out.write(tempbytes, 0, byteread); } 1、JAVA读取文件,避免中文乱码。 /** * 读取文件内容 * * @param filePathAndName * String 如c:\\1.txt 绝对路径 * @return boolean */ public static String readFile(String filePathAndName) { String fileContent = ""; try { File f = new File(filePathAndName); if(f.isFile()&&f.exists()){ InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8"); BufferedReader reader=new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { fileContent += line; } read.close(); } } catch (Exception e) { System.out.println("读取文件内容操作出错"); e.printStackTrace(); } return fileContent; } 2、JAVA写入文件,避免中文乱码。 public static void writeFile(String filePathAndName, String fileContent) { try { File f = new File(filePathAndName); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8"); BufferedWriter writer=new BufferedWriter(write); //PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName))); //PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName)); writer.write(fileContent); Java流 一、流的分类 ?按数据流动方向 –输入流:只能从中读取字节数据,而不能向其写出数据 –输出流:只能向其写入字节数据,而不能从中读取数据?按照流所处理的数据类型 –字节流:用于处理字节数据。 –字符流:用于处理Unicode字符数据。 ?按照流所处理的源 –节点流:从/向一个特定的IO设备读/写数据的流。(低级流)–处理流:对已存在的流进行连接和封装的流。(高级流)二、缓冲流 ?缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法。 ?J2SDK提供了四种缓存流: –BufferedReader –BufferedWriter –BufferedInputStream s –BufferedOutputStream ?缓冲输入流支持其父类的mark()和reset()方法: –mark()用于“标记”当前位置,就像加入了一个书签,可以使用reset()方法返回这个标记重新读取数据。?BufferedReader提供了readLine()方法用于读取一行字符串(以\r 或\n分隔)。 ?BufferedWriter提供了newLine()用于写入一个行分隔符。 ?对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush()方法将会使内存中的数据立刻写出。 三、类层次 3.1、InputStream类层次 3.2、OutputStream类层次 3.3、Reader类层次 3.4、Writer类层次 四、常用的字符流与字节流的转化 说明: 1.字节流用于读写诸如图像数据之类的原始字节流。 2.字符流用于读写诸如文件数据之类的字符流。 3.低级流能和外设交流。 4.高级流能提高效率。 5.InputStreamReader 是字节流通向字符流的桥梁。 6.OutputStreamWriter 是字符流通向字节流的桥梁。 一. 创建文件 (1)最常用的(获得一个固定路径下的文件对象) File parentFile = new File(“D:\\My Documents\\.....”);//参数是一个路径的字符串。 (2)在父目录创建一个名为child的文件对象,child 为文件对象的名字 File chileFile= new File(“D:\\My Documents\\.....”,String child); 或File chileFile= new File(parentFile,String child); 二,常见文件夹属性和方法 (1)createNewFile(); 该方法的作用是创建指定的文件。该方法只能用于创建文件,不能用于创建文 件夹,且文件路径中包含的文件夹必须存在 File file=new ("D:\\My Document\\text.txt"); file.createNewFile(); 这样就会在D盘下的My Document 创建text.txt的记事本(注意:首先得保 证D盘下有My Documen这个文件夹) (2)mkdir(); 根据File对象的名字(路径)创建一个目录(文件夹),如果是相对目录,则新建的目 录在当前目录下 (3)mkdirs(); 如果File对象名字有多级目录,则可以调用该方法一次性创建多级目录。 (4)exists(); 判断File对象指向的文件是否存在,返回一个boolean类型(5)isDirectory(); 判断File对象指向的文件是否为目录,返回一个boolean类型的值,true或者false。 (6)getName();获得文件名称(不带路径) (7)length(); 得到File对象指向文件的长度,以字节计算,返回一个长整形的值(long);注意:在 系统中,文件夹(目录)的大小为零,也就是不占用空间,使用length()时返回的是0 (8)delete(); 删除File对象所指定的文件 (9)isFile(); 判断File对象指向的文件是不是标准文件(就像图片,音乐文件等) 三,文件的属性和方法 1.File.separator 当前操作系统的名称分隔符,等于字符串“\”. 1、文件输入流 向文件中写入数据 Sink输出流 节点流-——文件节点 FileOutStream——字节形式存储内容 FileWriter——字符型式存储内容 import java.io.*; public class P1{ public static void main(String[]args)throws Exception{ //TODO Auto-generated method stub FileOutputStream out=new FileOutputStream("text.txt"); out.write('a'); String str="Hello world"; byte[]buffer=str.getBytes(); out.write(buffer); out.write(buffer,6,5); out.close(); } } 输出:aHello world!world 2、从文件中读取数据 Source输入流 节点流——文件节点 FileReader——字符文件 FileInputStream——字节文件 import java.io.*; public class P1{ public static void main(String[]args)throws Exception{ //TODO Auto-generated method stub FileInputStream input=new FileInputStream("text.txt"); int ch=input.read();//读入一个字节 while(ch!=-1) { System.out.print((char)ch); ch=input.read(); } input.close(); 1.保存对象到文件中 Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可: public static void writeObjectToFile(Object obj) { File file =new File("test.dat"); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut=new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); System.out.println("write object success!"); } catch (IOException e) { System.out.println("write object failed"); e.printStackTrace(); } } 参数obj一定要实现Serializable接口,否则会抛出 java.io.NotSerializableException异常。另外,如果写入的对象是一个容器,例如List、Map,也要保证容器中的每个元素也都是实现了Serializable 接口。例如,如果按照如下方法声明一个Hashmap,并调用writeObjectToFile方法就会抛出异常。但是如果是 Hashmap Java IO流和文件操作Java流操作有关的类或接口: Java流类图结构: 1、File类 File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。 构造方法摘要 File(File parent, String child) File(String pathname) File(String parent, String child) 构造函数 创建方法 1.boolean createNewFile() 不存在返回true 存在返回false 2.boolean mkdir() 创建目录 3.boolean mkdirs() 创建多级目录 删除方法 1.boolean delete() 2.boolean deleteOnExit() 文件使用完成后删除 例子1:列出指定文件夹的文件或文件夹 public class FileDemo1 { public static void main(String[] args){ File[] files =File.listRoots(); for(File file:files){ System.out.println(file); if(file.length()>0){ String[] filenames =file.list(); for(String filename:filenames){ System.out.println(filename); } } } } } 例子2:文件过滤 import java.io.File; public class FileTest2 { public static void main(String[] args) { File file = new File("file"); String[] names = file.list(); for(String name : names) { if(name.endsWith(".java")) { System.out.println(name); } java读入文本文件到TextArea(打开功能实现) Java语言: import java.awt.*; import java.io.*; import java.awt.event.*; public class IOtest extends Frame implements ActionListener{ private Frame f; private TextArea ta; //ta用于显示打开的内容 private Button btn; private FileDialog fd; private File file1 = null; //构造函数开始 public IOtest(){ btn = new Button("打开"); ta = new TextArea(5,50); btn.addActionListener(this);//给按钮添加事件监听器 } //给按钮添加行为 public void actionPerformed(ActionEvent e){ if (e.getSource()==btn) { //单击打开按钮时 fd = new FileDialog(f,"Open",FileDialog.LOAD); fd.setVisible(true); //创建并显示打开文件对话框 //if ((fd.getDirectory()!=null) && (fd.getFile()!=null)) { try { //以缓冲区方式读取文件内容 file1 = new File(fd.getDirectory(),fd.getFile()); FileReader fr = new FileReader(file1); BufferedReader br = new BufferedReader(fr); String aline; while ((aline=br.readLine()) != null)//按行读取文本 ta.append(aline+"\r\n"); fr.close(); br.close(); } catch (IOException ioe){ System.out.println(ioe); } } java读取word文档时,虽然网上介绍了很多插件poi、java2Word、jacob、itext等等,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定,做项目不太敢用);java2Word、jacob容易报错找不到注册,比较诡异,我曾经在不同的机器上试过,操作方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好办法。经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可。rtf格式文件表面看来和doc没啥区别,都可以用word打开,各种格式都可以设定。 ----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档。 ----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可。 1、采用字节的形式读取rtf模板内容 2、将可变的内容字符串转为rtf编码 3、替换原文中的可变部分,形成新的rtf文档 主要程序如下: /** * 将制定的字符串转换为rtf编码 */ public String bin2hex(String bin) { char[] digital = "0123456789ABCDEF".toCharArray(); StringBuffer sb = new StringBuffer(""); byte[] bs = bin.getBytes(); int bit; for (int i = 0; i < bs.length;i++) { bit = (bs[i] & 0x0f0) >> 4; sb.append("\\'"); sb.append(digital[bit]); bit = bs[i] & 0x0f; Java 对文件进行读写操作的例子很多,让初学者感到十分困惑,我觉得有必要将各种方法进行 一次分析,归类,理清不同方法之间的异同点。 一.在JDK 1.0 中,通常是用InputStream & OutputStream 这两个基类来进行读写操作的。InputStream 中的FileInputStream 类似一个文件句柄,通过它来对文件进行操作,类似的,在 OutputStream 中我们有FileOutputStream 这个对象。 用FileInputStream 来读取数据的常用方法是: FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); 用in.readLine() 来得到数据,然后用in.close() 关闭输入流。 完整代码见Example 1。 用FileOutputStream 来写入数据的常用方法是: FileOutputStream out out = new FileOutputStream("myfile.txt"); PrintStream p = new PrintStream( out ); 用p.println() 来写入数据,然后用p.close() 关闭输入。 完整代码见Example 2。 二.在JDK 1.1中,支持两个新的对象Reader & Writer,它们只能用来对文本文件进行操作,而 JDK1.1中的InputStream & OutputStream 可以对文本文件或二进制文件进行操作。 用FileReader 来读取文件的常用方法是: FileReader fr = new FileReader("mydata.txt"); BufferedReader br = new BufferedReader(fr); 用br.readLing() 来读出数据,然后用br.close() 关闭缓存,用fr.close() 关闭文件。 完整代码见Example 3。 用FileWriter 来写入文件的常用方法是: FileWriter fw = new FileWriter("mydata.txt"); PrintWriter out = new PrintWriter(fw); 在用out.print 或out.println 来往文件中写入数据,out.print 和out.println的唯一区别是后者写 入数据或会自动开一新行。写完后要记得用out.close() 关闭输出,用fw.close() 关闭文件。完整代码见Example 4。 -------------------------------------------------------------- following is the source code of examples------------------------------------------------------ Example 1: java中多种方式读文件,追加文件内容,对文件的各种操作 一、多种方式读文件内容。 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 2008-5-7 09:48 我思念的城市 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * @param fileName 文件的名 */ public static void readFileByBytes(String fileName){ File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while((tempbyte=in.read()) != -1){ System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); //一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); ReadFromFile.showAvailableBytes(in);java文件流操作
java创建txt文件并进行读写修改操作
Java读取txt文件中指定行内容
java对文件名的几个操作,获取文件扩展名,去掉扩展名
Java 输入输出流及文件读写详解
java读取上传excel文件和txt文件中的数据
Java读取Excel文件的几种方法
java文件读写代码
java读写文件避免中文乱码
Java流(文件读写操作)
java File文件操作和文件流的详解(福哥出品)
如何使用java语言向文件中输入数据和从文件中读取数据
java将对象保存到文件中从文件中读取对象
java输入输出流和文件操作
java读入文本文件到TextArea(打开功能实现)
java读取word文档
Java 对文件读写操作
java中多种方式读文件,追加文件内容,对文件的各种操作