java文件读写代码

合集下载

java四种方式读取文件

java四种方式读取文件

java四种⽅式读取⽂件读取⽂件的四种⽅式:按字节读取、按字符读取、按⾏读取、随机读取⼀、按字节读取//1.按字节读写⽂件,⽤FileInputStream、FileOutputStreamString path = "D:\\iotest.txt";File file = new File(path);InputStream in;//每次只读⼀个字节try {System.out.println("以字节为单位,每次读取⼀个字节");in = new FileInputStream(file);int c;while((c=in.read())!=-1){if(c!=13&&c!=10){ // \n回车的Ascall码是10 ,\r换⾏是Ascall码是13,不现实挥着换⾏System.out.println((char)c);}}} catch (FileNotFoundException e) {e.printStackTrace();}//每次读多个字节try {System.out.println("以字节为单位,每次读取多个字节");in = new FileInputStream(file);byte[] bytes = new byte[10]; //每次读是个字节,放到数组⾥int c;while((c=in.read(bytes))!=-1){System.out.println(Arrays.toString(bytes));}} catch (Exception e) {// TODO: handle exception}⼆、按字符读取//2.按字符读取⽂件,⽤InputStreamReader,OutputStreamReaderReader reader = null;try {//每次读取⼀个字符System.out.println("以字符为单位读取⽂件,每次读取⼀个字符");in = new FileInputStream(file);reader = new InputStreamReader(in);int c;while((c=reader.read())!=-1){if(c!=13&&c!=10){ // \n回车的Ascall码是10 ,\r换⾏是Ascall码是13,不现实挥着换⾏System.out.println((char)c);}}} catch (Exception e) {// TODO: handle exception}try {//每次读取多个字符System.out.println("以字符为单位读取⽂件,每次读取⼀个字符");in = new FileInputStream(file);reader = new InputStreamReader(in);int c;char[] chars = new char[5];while((c=reader.read(chars))!=-1){System.out.println(Arrays.toString(chars));}} catch (Exception e) {// TODO: handle exception}三、按⾏读取//3.按⾏读取⽂件try {System.out.println("按⾏读取⽂件内容");in = new FileInputStream(file);Reader reader2 = new InputStreamReader(in);BufferedReader bufferedReader = new BufferedReader(reader2);String line;while((line=bufferedReader.readLine())!=null){System.out.println(line);}bufferedReader.close();} catch (Exception e) {// TODO: handle exception}四、随机读取//4.随机读取try {System.out.println("随机读取⽂件");//以只读的⽅式打开⽂件RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");//获取⽂件长度,单位为字节long len = randomAccessFile.length();//⽂件起始位置int beginIndex = (len>4)?4:0;//将⽂件光标定位到⽂件起始位置randomAccessFile.seek(beginIndex);byte[] bytes = new byte[5];int c;while((c=randomAccessFile.read(bytes))!=-1){System.out.println(Arrays.toString(bytes));}} catch (Exception e) {// TODO: handle exception}。

java中easyexsl的用法

java中easyexsl的用法

java中easyexsl的用法Java中EasyExcel的用法在Java开发中,处理Excel文件是一项常见的任务。

而EasyExcel 作为一款优秀的Java Excel解决方案,提供了便捷的API,简化了Excel文件的读写操作。

本文将介绍Java中EasyExcel的用法,包括Excel文件的读取和写入操作。

一、Excel文件读取在使用EasyExcel读取Excel文件时,首先需要定义对应的Java实体类,用于映射Excel文件中的数据。

接着通过EasyExcel提供的监听器,实现对Excel文件的读取操作。

下面是一个简单的读取Excel文件的示例代码:```java// 定义Excel实体类@Datapublic class UserData {@ExcelProperty("姓名")private String name;@ExcelProperty("年龄")private Integer age;@ExcelProperty("性别")private String gender;}// 使用EasyExcel读取Excel文件String fileName = "test.xlsx";String sheetName = "Sheet1";EasyExcel.read(fileName, UserData.class, new AnalysisEventListener<UserData>() {@Overridepublic void invoke(UserData data, AnalysisContext context) {// 处理每一行数据}@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {// 读取完成后的操作}}).sheet(sheetName).doRead();```在`invoke`方法中处理每一行数据。

java 读取文件的最后100行代码

java 读取文件的最后100行代码

java 读取文件的最后100行代码在 Java 中读取文件的最后 100 行代码可以通过以下步骤实现:打开文件并获取文件的总行数。

移动文件指针到倒数第 100 行的位置。

从该位置开始读取文件直到文件末尾。

下面是一个简单的 Java 代码示例来实现这个功能:import java.io.*;public class ReadLast100LinesOfFile {public static void main(String[] args) {File file = new File("your_file_path");try {RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");long fileLength = file.length();long position = fileLength - 1;int linesCount = 0;// 从文件末尾开始逐字符读取,统计行数while (position >= 0) {randomAccessFile.seek(position);int readByte = randomAccessFile.read();if (readByte == '\n') {linesCount++;if (linesCount == 100) {break;}}position--;}// 如果文件行数不足100行,则从文件头开始读取if (position < 0) {randomAccessFile.seek(0);}// 读取文件最后100行内容String line;while ((line = randomAccessFile.readLine()) != null) {System.out.println(line);}randomAccessFile.close();} catch (IOException e) {e.printStackTrace();}}}请注意替换示例代码中的"your_file_path" 为你想要读取的文件的路径。

Java一次性读取或者写入文本文件所有内容

Java一次性读取或者写入文本文件所有内容

Java⼀次性读取或者写⼊⽂本⽂件所有内容⼀次性读取⽂本⽂件所有内容我们做⽂本处理的时候的最常⽤的就是读写⽂件了,尤其是读取⽂件,不论是什么⽂件,我都倾向于⼀次性将⽂本的原始内容直接读取到内存中再做处理,当然,这需要你有⼀台⼤内存的机器,内存不够者……可以⼀次读取少部分内容,分多次读取。

读取⽂件效率最快的⽅法就是⼀次全读进来,很多⼈⽤readline()之类的⽅法,可能需要反复访问⽂件,⽽且每次readline()都会调⽤编码转换,降低了速度,所以,在已知编码的情况下,按字节流⽅式先将⽂件都读⼊内存,再⼀次性编码转换是最快的⽅式,典型的代码如下:public String readToString(String fileName) {String encoding = "UTF-8";File file = new File(fileName);Long filelength = file.length();byte[] filecontent = new byte[filelength.intValue()];try {FileInputStream in = new FileInputStream(file);in.read(filecontent);in.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}try {return new String(filecontent, encoding);} catch (UnsupportedEncodingException e) {System.err.println("The OS does not support " + encoding);e.printStackTrace();return null;}}⼀次性写⼊⽂本⽂件所有内容/*** ⼀次性写⼊⽂本⽂件所有内容** @param fileName* @param content*/public static void saveStringTOFile(String fileName, String content){FileWriter writer=null;try {writer = new FileWriter(new File(fileName));writer.write(content);} catch (IOException e) {// TODO ⾃动⽣成的 catch 块e.printStackTrace();} finally {try {writer.close();} catch (IOException e) {// TODO ⾃动⽣成的 catch 块e.printStackTrace();}}System.out.println("写⼊成功!!!");}。

java 顺序读写文件的原理

java 顺序读写文件的原理

java 顺序读写文件的原理Java顺序读写文件的原理顺序读写文件是一种常见的文件操作方式,特别是用于处理大型文件或者需要按照固定顺序访问文件内容的情况。

Java提供了多种API和技术来实现顺序读写文件,下面将介绍其原理。

1. 读取文件(顺序读取):顺序读取文件主要通过FileInputStream类来实现。

以下是其原理:- 使用FileInputStream类的构造函数创建一个文件输入流对象,并指定要读取的文件路径。

- 创建一个字节数组或者字符数组作为缓冲区,用来存放从文件中读取的数据。

- 使用read方法从文件输入流中读取数据,并将数据存入缓冲区。

read方法会返回读取的字节数或者字符数,如果已经读取到文件末尾,则返回-1。

- 重复执行上述步骤,直到读取完整个文件内容。

2. 写入文件(顺序写入):顺序写入文件主要通过FileOutputStream类来实现。

以下是其原理:- 使用FileOutputStream类的构造函数创建一个文件输出流对象,并指定要写入的文件路径。

- 创建一个字节数组或者字符数组作为缓冲区,用来存放待写入的数据。

- 使用write方法将缓冲区中的数据写入文件输出流。

write方法会将数据写入文件并返回写入的字节数或者字符数。

- 重复执行上述步骤,直到写入完所有数据。

- 使用close方法关闭文件输出流,确保所有数据都被写入文件。

需要注意的是,顺序读写文件时要合理设置缓冲区的大小。

缓冲区太小会导致频繁的IO操作,影响性能;缓冲区太大则会占用过多内存。

因此,根据实际情况调整缓冲区大小以达到最佳性能。

另外,为了保证顺序读写文件的稳定性和可靠性,建议在读写文件时使用try-catch-finally或者try-with-resources语句块,确保资源能够被正确释放。

总结:顺序读写文件是通过Java的FileInputStream和FileOutputStream类来实现的。

java读取文件和写入文件的方式(简单实例)

java读取文件和写入文件的方式(简单实例)

java读取⽂件和写⼊⽂件的⽅式(简单实例)Java代码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);}} catch (Exception e1) {e1.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e1) {}}}}/*** 以字符为单位读取⽂件,常⽤于读⽂本,数字等类型的⽂件*/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这两个字符在⼀起时,表⽰⼀个换⾏。

java代码实现读写txt文件(txt文件转换成java文件)

java代码实现读写txt文件(txt文件转换成java文件)

29
30 /**
31 * 删除单个文件
32 *
33 * @param fileName
34 *
要删除的文件的文件名
35 * @return 单个文件删除成功返回true,否则返回false
36 */
37 public static boolean deleteFile(String fileName) {
64
fileOutputStream.close();
65
flag=true;
66
} catch (Exception e) {
80
}
81
//删除掉原来的文件
82
deleteFile(name01);
83
84
/* 输出数据 */
85
try {
86
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(name02)),
35
String result = "";
36
try {
37
InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"gbk");
38
BufferedReader br = new BufferedReader(reader);
59
boolean flag=false;
60
FileOutputStream fileOutputStream=null;

Java的RandomAccessFile对文件内容进行读写

Java的RandomAccessFile对文件内容进行读写

Java的RandomAccessFile对⽂件内容进⾏读写RandomAccessFile是Java提供的对⽂件内容的访问,她既可以读⽂件,也可以写⽂件,并且RandomAccessFile⽀持随机访问⽂件,也就是说他可以指定位置进⾏访问。

我们知道Java的⽂件模型,⽂件硬盘上的⽂件是byte byte byte的字节进⾏存储的,是数据的集合。

下⾯就是⽤这个类的步骤。

(1)打开指定的⽂件,有两种模式“rw”(读写) “r”(只读),创建对象,并且指定file和模式,例如:RandomAccessFile ac=new RandomAccessFile(file,”rw”);因为它⽀持随机访问⽂件,所以他引⼊了指针,可以通过指针来写⼊写出在指定的位置。

⽂件指针,打开⽂件时指针在开头pointer=0 (2)RandomAccessFile的往⽂件中写的⽅法(还有其他的写⽅法)Ac.write(int)----->只能写⼀个字节(后⼋位),同时⽂件指针也会移动,指向下⼀个位置。

(3)RandomAccessFile读的⽅法(还有其他的读⽅法)int b=ac.read()--->读⼀个字节(4)⽂件读写完毕后必须要把他关闭,调⽤close()的⽅法。

下⾯就是例⼦://创建相对路径的⽂件,就是在这个项⽬中创建⼀个⽂件夹File file=new File("random");if(!file.exists()) {file.mkdir();}File fileName=new File(file,"javaio.txt");if(!fileName.exists()) {fileName.createNewFile();//创建⽂件}//创建⼀个RandomAccessFile的对象,并指定模式rw,能读能写,//注意:必须是⽂件,不能是路径RandomAccessFile raf=new RandomAccessFile(fileName,"rw");//获取此时的⽂件指针的位置,起始位置为0System.out.println(raf.getFilePointer());//向⽂件中写⼊字符A,字符类型有两个字节,但她写⼊的是后⼋位的字节//字符A正好可以⽤后⼋位的字节表⽰出来raf.write('A');//字符的位置会⾃动向后移动,⽂件指针会向后⾃动移动System.out.println("输⼊⼀个字符之后,⽂件指针的位置"+raf.getFilePointer());raf.write('B');//每次write只能写⼊⼀个字节,如果要把i写进去,就需要写四次int i=0x7fffffff;raf.write(i>>>24 & 0xff);//写⼊⾼⼋位的raf.write(i>>>16 & 0xff);raf.write(i>>>8 & 0xff);raf.write(i);//写⼊低⼋位System.out.println("写⼊整数的时候⽂件指针的位置是"+raf.getFilePointer());/*** writeInt()的内置⽅法* public final void writeInt(int v) throws IOException {write((v >>> 24) & 0xFF);write((v >>> 16) & 0xFF);write((v >>> 8) & 0xFF);write((v >>> 0) & 0xFF);//written += 4;}*///也可以直接写⼊int整数raf.writeInt(i);//写⼊⼀个汉字,汉字为两个字节String str="欢迎学习java";byte[] b=str.getBytes("gbk");raf.write(b);System.out.println("此时的长度为"+raf.length());//读⽂件必须将⽂件指针放在开头位置raf.seek(0);byte[] buf=new byte[(int)raf.length()];raf.read(buf);//将内容写⼊buf字节数组中String str1=new String(buf,"gbk");System.out.println("⽂件中的内容为"+str1); raf.close();。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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);}} catch (Exception e1) {e1.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e1) {}}}}/*** 以字符为单位读取文件,常用于读文本,数字等类型的文件*/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 < charread; 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) {}}}}/*** 以行为单位读取文件,常用于读面向行的格式化文件*/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) {}}}}/*** 随机读取文件内容*/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个字节,则读剩下的字节。

// 将一次读取的字节数赋给bytereadwhile ((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) {}}}}/*** 显示输入流中还剩的字节数*/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); }}。

相关文档
最新文档