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中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 行代码可以通过以下步骤实现:打开文件并获取文件的总行数。
移动文件指针到倒数第 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⼀次性读取或者写⼊⽂本⽂件所有内容⼀次性读取⽂本⽂件所有内容我们做⽂本处理的时候的最常⽤的就是读写⽂件了,尤其是读取⽂件,不论是什么⽂件,我都倾向于⼀次性将⽂本的原始内容直接读取到内存中再做处理,当然,这需要你有⼀台⼤内存的机器,内存不够者……可以⼀次读取少部分内容,分多次读取。
读取⽂件效率最快的⽅法就是⼀次全读进来,很多⼈⽤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提供了多种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代码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文件)
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对⽂件内容进⾏读写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();。
java读写yml文件,修改文件内容保持原格式
java读写yml⽂件,修改⽂件内容保持原格式我理解的yml⽂件在我们学习过springboot项⽬的同学对这个⽂件肯定是特别熟悉,通常我们都是⽤它来修改保存我们的项⽬配置,最简单的就是数据库的配置,然后就是资源读取配置,redies配置,缓存配置,以及jwt的配置等等,因为yml⽂件主要⽤于我们的项⽬配置,所以⼀个特点就是易于⼈们阅读,修改;即使⼀个刚接触yml⽂件的⼈加上简单的注释,肯定也能够看懂打部分内容的;我总结的特点就是:1. 直观,易于阅读,修改2. 可以把对象的层次结构展现得很直观3. ⽤key:value的⽅式属性4. ⽤空格数量表⽰层级关系我⼯作中遇到的问题⼤家估计在spring中主要都是读取yml⽂件,所以对于写yml⽂件的过程经历不太多,我的项⽬系统是⾃⼰的java框架,然后要集成另外的⼀个spring项⽬,当我的项⽬修改数据库信息的时候同时也要修改这个springboot项⽬的数据库配置信息,那么就存在⼀个对yml的读和写的过程,我经过百度后加上⾃⼰的代码,就得到了⾃⼰想要的效果;主要⽤到了ymal这个开源⼯具类;maven依赖<dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.25</version></dependency>读取关键代码,ymal⼯具⾃动将yml⽂件转换为map结构的对象//解析yml⽂件的关键类Yaml yml =null;try (FileInputStream in = new FileInputStream(file)){yml = new Yaml();obj = (Map)yml.load(in);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Map<String,Object> springMap =(Map)obj.get("spring");写⼊关键代码,try (FileWriter writer = new FileWriter(file)) {//writer.write(yml.dump(obj));writer.write(yml.dumpAsMap(obj));//writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.BLOCK));//可以⾃定义写⼊格式//writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.FLOW));} catch (IOException e) {e.printStackTrace();}我⽤的是dumpAsMap⽅法,这个⽅法能够⾃动把map结构的对象转为yml⽂件的key:value的结构,map层级⽤两个空格表⽰,但是我的这个项⽬⽤了4个空格,所以后⾯我还得重新特殊处理⼀下;完整代码,因为我的主要⽬的是修改数据库配置信息,由于项⽬系统⽀持了很多类型的数据库,所以我要适配各种数据库;@SpringBootTestpublic class DemoTest {@Testpublic void readYmlTest() {//要读的⽂件路径String filePath ="C:"+File.separator+"Users"+File.separator+"17247"+File.separator+"Desktop"+File.separator+"application-exclusive.yml";Map<String,Object> obj =null;File file = new File(filePath);//解析yml⽂件的关键类Yaml yml =null;try (FileInputStream in = new FileInputStream(file)){yml = new Yaml();obj = (Map)yml.load(in);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Map<String,Object> springMap =(Map)obj.get("spring");String url = "jdbc:oracle:thin:@127.0.0.1:1521/orcl";//String url = "jdbc:dm://127.0.0.1:5236/DMSERVER?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8"; String usesrname = "poc";String pwd = "ENC(w2PXuzg+U60Zs2MA/FouyQ==)";AEDatasourceFactory AeDatasourceFactory = new AEDatasourceFactory(url,usesrname,pwd);//根据不同数据库更新模板AeDatasourceFactory.updateDatasourceTemplet(springMap);try (FileWriter writer = new FileWriter(file)) {//writer.write(yml.dump(obj));//writer.write(yml.dumpAsMap(obj));writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.BLOCK));//writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.BLOCK));} catch (IOException e) {e.printStackTrace();}//重新读取⽂件调整空格StringBuffer buffer = new StringBuffer();String newLine =System.lineSeparator();try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));) {String line;while ((line = input.readLine()) != null) {String lineTrim = line.trim();String pre ="";if(line.startsWith(" ")){int length = line.length()-lineTrim.length();pre = this.getSpaceByNum(length*2);}if(lineTrim.startsWith("- ")){//有横杠的需要再加4个空格pre = pre+this.getSpaceByNum(4);}buffer.append(pre+lineTrim);buffer.append(newLine);}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, false), "utf-8"))) {writer.write(buffer.toString());} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}//获取指定数量的空格private String getSpaceByNum(int num){StringBuffer buffer = new StringBuffer();for(int i=0;i<num;i++){buffer.append(" ");}return buffer.toString();}private String getAEEncryptPassword(String input) {return input ;}}适配数据库⼯⼚类import java.util.LinkedHashMap;import java.util.Map;/*** AE数据源模板⼯⼚类*/public class AEDatasourceFactory {//oracle数据库private final String ORACLE_TYPE="jdbc:oracle";//sqlserver数据库类型private final String SQLSERVER_TYPE="jdbc:oracle";//db2数据库private final String DB2_TYPE="jdbc:db2";//达梦数据库private final String DM_TYPE="jdbc:dm";//pg数据库private final String PG_TYPE="dbc:postgresql";//⾼斯数据库private final String GAUSS_TYPE="jdbc:zenith";String url;String username;String password;public AEDatasourceFactory(String url, String username, String password) {this.url=url;ername=username;this.password=password;}/*** 获取更新数据源模板* @param springMap*/public void updateDatasourceTemplet(Map<String,Object> springMap){Map<String,Object> dataSource = (Map<String,Object>)springMap.get("datasource");Map<String,Object> jpaMap = (Map<String,Object>)dataSource.get("jpa");if(jpaMap==null){//应该是jpa和datasource同级的,// 但是他们提供的可能是不同级的jpaMap = springMap.get("jpa")!=null?(Map<String,Object>)springMap.get("jpa"):new LinkedHashMap<>(); }dataSource.clear();Map<String,Object> hikari = new LinkedHashMap<>();hikari.put("auto-commit",false);if(url.startsWith(ORACLE_TYPE) || url.startsWith(SQLSERVER_TYPE)){dataSource.put("type","com.zaxxer.hikari.HikariDataSource");dataSource.put("url",url);dataSource.put("username",username);dataSource.put("password",getAEEncryptPassword(password));dataSource.put("hikari",hikari);}else if(url.startsWith(DM_TYPE)){dataSource.put("url",url);dataSource.put("username",username);dataSource.put("password",getAEEncryptPassword(password));dataSource.put("driver-class-name","dm.jdbc.driver.DmDriver");}else if(url.startsWith(DB2_TYPE)){dataSource.put("type","com.zaxxer.hikari.HikariDataSource");dataSource.put("driver-class-name","com.ibm.db2.jcc.DB2Driver");dataSource.put("hikari",hikari);}else if(url.startsWith(GAUSS_TYPE)){dataSource.put("url",url);dataSource.put("username",username);dataSource.put("password",getAEEncryptPassword(password));dataSource.put("driver-class-name","com.huawei.gauss.jdbc.ZenithDriver");}else if(url.startsWith(PG_TYPE)){dataSource.put("type","com.zaxxer.hikari.HikariDataSource");dataSource.put("url",url);dataSource.put("username",username);dataSource.put("password",getAEEncryptPassword(password));dataSource.put("hikari",hikari);//pg没有jpajpaMap=null;}if(jpaMap!=null){getJpaTemplet(jpaMap);springMap.put("jpa",jpaMap);}}private void getJpaTemplet(Map<String,Object> jpaMap){if(jpaMap==null){return;}jpaMap.clear();Map<String,Object> properties = new LinkedHashMap<>();if(url.startsWith(ORACLE_TYPE) || url.startsWith(SQLSERVER_TYPE)){jpaMap.put("database-platform","org.hibernate.dialect.Oracle12cDialect");jpaMap.put("database","ORACLE");jpaMap.put("show-sql",false);properties.put("hibernate.id.new_generator_mappings",true);properties.put("hibernate.connection.provider_disables_autocommit",true);properties.put("e_second_level_cache",false);properties.put("e_query_cache",false);properties.put("hibernate.generate_statistics",false);jpaMap.put("properties",properties);}else if(url.startsWith(GAUSS_TYPE)){//不知道为啥要⽤oracle的properties.put("hibernate.dialect","org.hibernate.dialect.Oracle12cDialect");jpaMap.put("properties",properties);}else if(url.startsWith(DM_TYPE)){properties.put("hibernate.dialect","org.hibernate.dialect.DmDialect");jpaMap.put("properties",properties);}else if(url.startsWith(PG_TYPE)){}else if(url.startsWith(DB2_TYPE)){properties.put("hibernate.dialect","com.diwork.intelliv.workbench.auth.dialect.CustomDB2Dialect");properties.put("hibernate.auto_quote_keyword",true);jpaMap.put("properties",properties);jpaMap.put("show-sql",true);Map<String,Object> hibernate = new LinkedHashMap<>();Map<String,Object> naming = new LinkedHashMap<>();naming.put("physical-strategy","org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"); hibernate.put("naming",naming);jpaMap.put("hibernate",hibernate);}}//密码加密⽅法private String getAEEncryptPassword(String input) {return input ;}}这样修改了指定的内容,⽽且还保证了⽂件的原格式,但有个问题是⽂件的注释会丢失;。
java文件读写
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import java.util.Scanner;import java.io.RandomAccessFile;import java.io.FileOutputStream;import java.io.OutputStreamWriter;public class WRFile{//属性private String inStr=""; //输入数据private String outStr; //输出数据//方法public String read(String path) //读文件{BufferedReader br=null;inStr=""; //防止重复相加,读之前先置输入数据为空try{br=new BufferedReader(new FileReader(path));String str=null;while((str=br.readLine())!=null){inStr+=str+"\n"; //连接每一行,并在其后加上换行符 }}catch(Exception e){e.printStackTrace();}finally{if(br!=null)try{br.close();}catch(Exception e){e.printStackTrace();}}return inStr;}public void rewrite(String path,String str) //写文件{BufferedWriter bw=null;try{bw=new BufferedWriter(new FileWriter(path));outStr=str;bw.write(outStr);}catch(Exception e){e.printStackTrace();}finally{if(bw!=null)try{bw.close();}catch(Exception e){e.printStackTrace();}}}public void addwrite(String path,String str){BufferedWriter bw=null;try{bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path,true))); //追加文件outStr=str;bw.write(outStr+"\r\n");}catch(Exception e){e.printStackTrace();}finally{if(bw!=null)try{bw.close();}catch(Exception e){e.printStackTrace();}}}public void writeAppend(String path,String str){RandomAccessFile rf=null;try{outStr=str;rf=new RandomAccessFile(path,"rw"); //读写模式随机访问rf.seek(rf.length());rf.writeUTF(outStr+"\r\n"); //乱码}catch(Exception e){e.printStackTrace();}finally{if(rf!=null)try{rf.close();}catch(Exception e){e.printStackTrace();}}}//主函数public static void main(String[] args){Scanner sc=new Scanner(System.in);outer: while(true){System.out.println("请输入文件路径:");String path=sc.nextLine();WRFile wrf=new WRFile();inner: while(true){System.out.println("请选择操作:1.读文件 2.写文件 3.追加写文件 4.结束本文件的操作 5.退出");Scanner sc1=new Scanner(System.in);int choices=sc1.nextInt();switch(choices){case 1:// System.out.println("path="+path+"\tchoices="+choices);System.out.println( wrf.read(path));break;case 2://System.out.println("path="+path+"\tchoices="+choices);System.out.println("请输入需要重新写入的数据");Scanner sc2=new Scanner(System.in);String str1=sc.nextLine();wrf.rewrite(path,str1);break;case 3://System.out.println("path="+path+"\tchoices="+choices);System.out.println("请输入需要追加写入的数据");Scanner sc3=new Scanner(System.in);String str2=sc3.nextLine();wrf.addwrite(path,str2);// wrf.writeAppend(path,str2);break;case 4:break inner; //结束内存循环case 5:break outer; //退出外层循环default:System.out.println("您输入的有误,请重新输入!");}}}}}。
java的filereader和filewriter类使用示例
java的filereader和filewriter类使用示例如何在Java中使用FileReader和FileWriter类进行文件的读写操作。
在本文中,我们将详细讨论这两个类的使用方法,并给出相应的示例代码。
一、FileReader类的使用示例FileReader类是Java IO库中提供的一个用于读取字符文件的类。
它继承自Reader类,提供了一系列用于读取字符数据的方法。
下面是使用FileReader类进行文件读取操作的步骤:1. 创建一个FileReader对象,需要指定要读取的文件路径。
例如,要读取名为"example.txt"的文件,可以使用以下代码创建一个FileReader对象:FileReader fr = new FileReader("example.txt");2. 使用FileReader对象的read()方法读取文件内容。
read()方法会返回一个int类型的值,代表读取的字符。
如果已经到达文件的末尾,则返回-1。
以下是一个示例代码:int character;while ((character = fr.read()) != -1) {System.out.print((char)character);}3. 关闭FileReader对象。
在读取文件结束后,需要调用close()方法关闭FileReader对象,以释放资源。
例如:fr.close();以上就是使用FileReader类进行文件读取操作的步骤。
接下来我们将详细介绍FileWriter类的使用方法。
二、FileWriter类的使用示例FileWriter类是Java IO库中提供的一个用于写入字符文件的类。
它继承自Writer类,提供了一系列用于写入字符数据的方法。
下面是使用FileWriter类进行文件写入操作的步骤:1. 创建一个FileWriter对象,需要指定要写入的文件路径。
用java逐行读取和写入大文件的最快方法
在软件开发过程中,经常会遇到需要处理大文件的情况,而对于Java语言来说,如何高效地逐行读取和写入大文件是一个常见的问题。
本文将介绍使用Java语言逐行读取和写入大文件的最快方法,帮助开发人员更加高效地处理大文件。
一、使用BufferedReader和BufferedWriter进行逐行读取和写入BufferedReader和BufferedWriter是Java标准库中提供的用于缓冲输入和输出的类,它们可以显著提高文件读写的效率。
下面是使用BufferedReader和BufferedWriter进行逐行读取和写入的代码示例:```javapublic class FileUtil {public static void copyFile(String sourceFileName, String targetFileName) {try (BufferedReader br = new BufferedReader(new FileReader(sourceFileName));BufferedWriter bw = new BufferedWriter(new FileWriter(targetFileName))) {String line;while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();}} catch (IOException e) {e.printStackTrace();}}}```在上面的代码中,我们使用了BufferedReader逐行读取文件,并使用BufferedWriter逐行写入文件,通过缓冲输入和输出来提高读写效率。
这种方法适用于处理中等大小的文件,但对于大文件来说,还有更加高效的方法可供选择。
二、使用RandomAccessFile进行逐行读取和写入RandomAccessFile是Java标准库中提供的用于随机访问文件的类,它可以在文件中进行任意位置的读写操作。
Java读写Excel文件DEMO
Java读写Excel⽂件DEMO下载⼀定格式的Excel⽂件: @RequestMapping("/xxxx/xxxx/xxxx/copyfiledownload")@ResponseBodypublic void copyfiledownload(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{response.setContentType("text/html; charset=GBK");String basePath = request.getSession().getServletContext().getRealPath("/");File file = new File(basePath + "xxxx.xls");FileOutputStream fos=new FileOutputStream(file);HSSFWorkbook wb=new HSSFWorkbook();HSSFSheet sheet=wb.createSheet();wb.setSheetName(0, "sheet0");HSSFRow row=null;HSSFCell cell=null;row=sheet.createRow(0);cell=row.createCell(0);cell.setCellValue("xxID");cell=row.createCell(1);cell.setCellValue("每ID的总限量");cell=row.createCell(2);cell.setCellValue("每⽤户对此ID最⼤购买量");cell=row.createCell(3);cell.setCellValue("xx售卖价格");cell=row.createCell(4);cell.setCellValue("S时间");cell=row.createCell(5);cell.setCellValue("X时间");CellStyle cellStyle = wb.createCellStyle();CreationHelper helperDate = wb.getCreationHelper();cellStyle.setDataFormat(helperDate.createDataFormat().getFormat("yy/mm/dd/ hh:mm:ss"));HSSFRow rowD=null;HSSFCell cellD=null;for (int i = 1; i < 1000; i++) {rowD=sheet.createRow(i);cellD=rowD.createCell(4);cellD.setCellStyle(cellStyle);cellD=rowD.createCell(5);cellD.setCellStyle(cellStyle);} // 设置时间格式cell=row.createCell(6);cell.setCellValue("xx平台");//CellRangeAddressList(firstRow, lastRow, firstCol, lastCol)设置⾏列范围CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, 6, 6);String[] pos = {"PC","WAP","APP","PC+WAP","PC+APP","WAP+APP","PC+WAP+APP"};DataValidationHelper helper = sheet.getDataValidationHelper();DataValidationConstraint constraint = helper.createExplicitListConstraint(pos);DataValidation dataValidation = helper.createValidation(constraint, addressList);if(dataValidation instanceof XSSFDataValidation) {dataValidation.setSuppressDropDownArrow(true);dataValidation.setShowErrorBox(true);}else {dataValidation.setSuppressDropDownArrow(false);}sheet.addValidationData(dataValidation);wb.write(fos);fos.close();response.setContentType("application/x-msdownload");response.setContentLength((int) file.length());response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("gbk"), "iso-8859-1")); FileInputStream fis = new FileInputStream(file);BufferedInputStream buff = new BufferedInputStream(fis);byte[] b = new byte[1024];long k = 0;OutputStream myout = response.getOutputStream();while (k < file.length()) {int j = buff.read(b, 0, 1024);k += j;myout.write(b, 0, j);}myout.flush();buff.close();fis.close();myout.close();file.delete();}Excel⽂件读取: /*** 读取excel表头** @param file* @return* @throws IOException*/@SuppressWarnings("unused")private String[] readExcelHead(File file) throws IOException {HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));HSSFSheet sheet = wb.getSheetAt(0);HSSFRow row = null;HSSFCell cell = null;row = sheet.getRow(0);String[] buff = new String[row.getLastCellNum()];for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {cell = row.getCell(i);buff[i] = cell.getStringCellValue();}return buff;} /*** 读取2003excel** @param file* @return*/private List<List<Object>> read2003Excel(File file) throws IOException {List<List<Object>> dataList = new ArrayList<List<Object>>();HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));HSSFSheet sheet = wb.getSheetAt(0);HSSFRow row = null;HSSFCell cell = null;Object val = null;DecimalFormat df = new DecimalFormat("0");// 格式化数字DecimalFormat df2 = new DecimalFormat("#0.00");// 格式化⼩数SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化⽇期字符串for (int i = sheet.getFirstRowNum() + 1; i < sheet.getPhysicalNumberOfRows(); i++) {row = sheet.getRow(i);if (row == null) {continue;}List<Object> objList = new ArrayList<Object>();for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {cell = row.getCell(j);if (cell == null) {val = null;objList.add(val);continue;}switch (cell.getCellType()) {case HSSFCell.CELL_TYPE_STRING:val = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_NUMERIC:if ("@".equals(cell.getCellStyle().getDataFormatString())) {if (j == 3) {val = df2.format(cell.getNumericCellValue());} else {val = df.format(cell.getNumericCellValue());}} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {if (j == 3) {val = df2.format(cell.getNumericCellValue());} else {val = df.format(cell.getNumericCellValue());}} else {val = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));}break;case HSSFCell.CELL_TYPE_BOOLEAN:val = cell.getBooleanCellValue();break;case HSSFCell.CELL_TYPE_BLANK:val = "";break;default:val = cell.toString();break;}objList.add(val);}dataList.add(objList);}return dataList;} /*** 读取2007excel** @param file* @return*/private List<List<Object>> read2007Excel(File file) throws IOException {List<List<Object>> dataList = new ArrayList<List<Object>>();XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));XSSFSheet sheet = xwb.getSheetAt(0);XSSFRow row = null;XSSFCell cell = null;Object val = null;DecimalFormat df = new DecimalFormat("0");// 格式化数字DecimalFormat df2 = new DecimalFormat("#0.00");// 格式化⼩数SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化⽇期字符串for (int i = sheet.getFirstRowNum() + 1; i < sheet.getPhysicalNumberOfRows(); i++) {row = sheet.getRow(i);if (row == null) {continue;}List<Object> objList = new ArrayList<Object>();for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {cell = row.getCell(j);if (cell == null) {val = null;objList.add(val);continue;}switch (cell.getCellType()) {case XSSFCell.CELL_TYPE_STRING:val = cell.getStringCellValue();break;case XSSFCell.CELL_TYPE_NUMERIC:if ("@".equals(cell.getCellStyle().getDataFormatString())) {if (j == 3) {val = df2.format(cell.getNumericCellValue());} else {val = df.format(cell.getNumericCellValue());}} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {if (j == 3) {val = df2.format(cell.getNumericCellValue());} else {val = df.format(cell.getNumericCellValue());}} else {val = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));}break;case XSSFCell.CELL_TYPE_BOOLEAN:val = cell.getBooleanCellValue();break;case XSSFCell.CELL_TYPE_BLANK:val = "";break;default:val = cell.toString();break;}objList.add(val);}dataList.add(objList);}return dataList;}。
Java读写Excel文件中数据的简便方法(附代码)
Java读写Excel文件中数据的简便方法Java开发项目中经常会碰到处理Excel文件中数据的情况,这里通过一个例子来看一下实现方法:从Excel文件orders.xls中读取订单信息,从中找出2010年1月1日(含)之后,并且SELLERID等于18的订单。
找到的数据写入order_result.xls文件。
Excel文件orders.xls的内容如下:ORDERID CLIE NT SE LLERID AMOUNT ORDERDATE1 UJRNP 17 392 2008/11/2 15:282 SJCH 6 4802 2008/11/9 15:283 UJRNP 16 13500 2008/11/5 15:284 P WQ 9 26100 2008/11/8 15:285 P WQ 11 4410 2008/11/12 15:286 HANAR 18 6174 2008/11/7 15:287 E GU 2 17800 2008/11/6 15:288 VILJX 7 2156 2008/11/9 15:289 JAYB 14 17400 2008/11/12 15:2810 JAXE 19 19200 2008/11/12 15:2811 SJCH 7 13700 2008/11/10 15:2812 QUICK 11 21200 2008/11/13 15:2813 HL 12 21400 2008/11/21 15:2814 JAYB 1 7644 2008/11/16 15:2815 MIP 16 3234 2008/11/19 15:2816 AYW YN 4 6566 2008/11/21 15:28…Java程序的编写思路是1、从Excel文件逐行读入数据保存到List对象sourceList中。
2、遍历List对象sourceList,如果满足条件就保存到结果List对象resultList中。
javabyte【】数组与文件读写(增加新功能)
javabyte【】数组与⽂件读写(增加新功能)今天在测试直接写的⽂章:时,想调⽤FileHelper类对字节数组以追加的⽅式写⽂件,结果⽆论怎样竟然数据录⼊不全,重新看了下⽂件的追加模式,提供了两种⽅式:⽅式⼀:字节数组写⼊⽂件(不追加)//将byte数组写⼊⽂件public void createFile(String path, byte[] content) throws IOException {FileOutputStream fos = new FileOutputStream(path);fos.write(content);fos.close();}在此基础上更改为:字节数组写⼊⽂件(追加)/* ⽅法1:* 将byte数组(追加)写⼊⽂件** */public void createFileAdd(String path, byte[] content, boolean Appendable) throws IOException {// 程序写好之后每次存储数据都刷新//FileOutputStream fos = new FileOutputStream(path);// 研究了⼀下,原来FileOutPutStream也可以设置模式的,只是和openFileOutput不⼀样我这样写FileOutputStream fos=new FileOutputStream(_sdpath1,Appendable);就可以实现数据追加功能 FileOutputStream fos=new FileOutputStream(path,Appendable);fos.write(content);fos.write("\r\n".getBytes());fos.close();}⽅式⼆:直接写⼀个⽅法,该⽅法中的核⼼代码在需要哪种⽅式(追加或者不追加)时,注释更改即可/*** ⽅法⼆:* 根据byte数组,⽣成⽂件*/public void writeFile(byte[] bfile, String filePath,String fileName) {BufferedOutputStream bos = null;File file = null;try {File dir = new File(filePath);if(!dir.exists()&&dir.isDirectory()){//判断⽂件⽬录是否存在dir.mkdirs();}file = new File(filePath+"\\"+fileName);/* 使⽤以下2⾏代码时,不追加⽅式*//*bos = new BufferedOutputStream(new FileOutputStream(file));bos.write(bfile); *//* 使⽤以下3⾏代码时,追加⽅式*/bos = new BufferedOutputStream(new FileOutputStream(file, true));bos.write(bfile);bos.write("\r\n".getBytes());bos.flush();} catch (Exception e) {e.printStackTrace();} finally {if (bos != null) {try {bos.close();} catch (IOException e1) {e1.printStackTrace();}}}}总之,对字节数组的操作类,提供上来,供以后复习⽤:1import java.io.BufferedOutputStream;2import java.io.BufferedWriter;3import java.io.ByteArrayOutputStream;4import java.io.File;5import java.io.FileInputStream;6import java.io.FileOutputStream;7import java.io.FileWriter;8import java.io.IOException;9import java.io.OutputStreamWriter;1011public class FileHelper {12//第⼀种获取⽂件内容⽅式13public byte[] getContent(String filePath) throws IOException {14 File file = new File(filePath);1516long fileSize = file.length();17if (fileSize > Integer.MAX_VALUE) {18 System.out.println("file too big...");19return null;20 }2122 FileInputStream fi = new FileInputStream(file);2324byte[] buffer = new byte[(int) fileSize];2526int offset = 0;2728int numRead = 0;2930while (offset < buffer.length3132 && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {3334 offset += numRead;3536 }3738// 确保所有数据均被读取3940if (offset != buffer.length) {4142throw new IOException("Could not completely read file "+ file.getName());4344 }4546 fi.close();4748return buffer;49 }5051//第⼆种获取⽂件内容⽅式52public byte[] getContent2(String filePath) throws IOException53 {54 FileInputStream in=new FileInputStream(filePath);5556 ByteArrayOutputStream out=new ByteArrayOutputStream(1024);5758 System.out.println("bytes available:"+in.available());5960byte[] temp=new byte[1024];6162int size=0;6364while((size=in.read(temp))!=-1)65 {66 out.write(temp,0,size);67 }6869 in.close();7071byte[] bytes=out.toByteArray();72 System.out.println("bytes size got is:"+bytes.length);7374return bytes;75 }76//将byte数组写⼊⽂件77public void createFile(String path, byte[] content) throws IOException {7879 FileOutputStream fos = new FileOutputStream(path);8081 fos.write(content);82 fos.close();83 }84/* ⽅法1:85 * 将byte数组(追加)写⼊⽂件86 *87 * */88public void createFileAdd(String path, byte[] content, boolean Appendable) throws IOException {89// 程序写好之后每次存储数据都刷新90//FileOutputStream fos = new FileOutputStream(path);91// 研究了⼀下,原来FileOutPutStream也可以设置模式的,只是和openFileOutput不⼀样我这样写FileOutputStream fos=new FileOutputStream(_sdpath1,Appendable);就可以实现数据追加功能92 FileOutputStream fos=new FileOutputStream(path,Appendable);93 fos.write(content);94 fos.write("\r\n".getBytes());95 fos.close();96 }97/**98 * ⽅法⼆:99 * 根据byte数组,⽣成⽂件100*/101public void writeFile(byte[] bfile, String filePath,String fileName) {102 BufferedOutputStream bos = null;103104 File file = null;105try {106 File dir = new File(filePath);107if(!dir.exists()&&dir.isDirectory()){//判断⽂件⽬录是否存在108 dir.mkdirs();109 }110 file = new File(filePath+"\\"+fileName);111/* 使⽤以下2⾏代码时,不追加⽅式*/112/*bos = new BufferedOutputStream(new FileOutputStream(file));113 bos.write(bfile); */114115/* 使⽤以下3⾏代码时,追加⽅式*/116 bos = new BufferedOutputStream(new FileOutputStream(file, true)); 117 bos.write(bfile);118 bos.write("\r\n".getBytes());119120121 bos.flush();122123 } catch (Exception e) {124 e.printStackTrace();125 } finally {126if (bos != null) {127try {128 bos.close();129 } catch (IOException e1) {130 e1.printStackTrace();131 }132 }133134 }135 }136 }FileHelper.java。
lesson11-05 Java文件读写 -- zip文件读写
Java 核心技术第十一章Java文件读写第五节Zip文件读写1Java zip 包•压缩包:zip, rar, gz, ……•Java zip 包支持Zip和Gzip包的压缩和解压•zip文件操作类: java.util.zip包中–java.io.InputStream, java.io.OutputStream的子类–ZipInputStream, ZipOutputSream 压缩文件输入/输出流–ZipEntry 压缩项压缩•单个/多个压缩–打开输出zip文件–添加一个ZipEntry–打开一个输入文件,读数据,向ZipEntry写数据,关闭输入文件–重复以上两个步骤,写入多个文件到zip文件中–关闭zip文件–查看SingleFileZip.java 和MultipleFileZip.java解压•单个/多个解压–打开输入的zip文件–获取下一个ZipEntry–新建一个目标文件,从ZipEntry读取数据,向目标文件写入数据,关闭目标文件–重复以上两个步骤,从zip包中读取数据到多个目标文件–关闭zip文件–查看SingleFileUnzip.java 和MultipleFileUnzip.java总结•Java支持Zip和Gzip文件解压缩•重点在Entry和输入输出流向, 无需关注压缩算法代码(1) SingleFileZip.java代码(2) MultipleFileZip.java代码(3) MultipleFileZip.java代码(4) SingleFileUnzip.java代码(5) MultipleFileUnzip.java代码(6) MultipleFileUnzip.java代码(7) MultipleFileUnzip.java谢谢!13。
Java使用FileInputStream流读取文件示例详解
Java使⽤FileInputStream流读取⽂件⽰例详解⼀、File流概念JAVA中针对⽂件的读写操作设置了⼀系列的流,其中主要有FileInputStream,FileOutputStream,FileReader,FileWriter四种最为常⽤的流⼆、FileInputStream1)FileInputStream概念FileInputStream流被称为⽂件字节输⼊流,意思指对⽂件数据以字节的形式进⾏读取操作如读取图⽚视频等2)构造⽅法2.1)通过打开与File类对象代表的实际⽂件的链接来创建FileInputStream流对象public FileInputStream(File file) throws FileNotFoundException{}若File类对象的所代表的⽂件不存在;不是⽂件是⽬录;或者其他原因不能打开的话,则会抛出FileNotFoundException/**** 运⾏会产⽣异常并被扑捉--因为不存在xxxxxxxx这样的⽂件*/public static void main(String[] args){File file=new File("xxxxxxxx"); //根据路径创建File类对象--这⾥路径即使错误也不会报错,因为只是产⽣File对象,还并未与计算机⽂件读写有关联try{FileInputStream fileInputStream=new FileInputStream(file);//与根据File类对象的所代表的实际⽂件建⽴链接创建fileInputStream对象}catch (FileNotFoundException e){System.out.println("⽂件不存在或者⽂件不可读或者⽂件是⽬录");}}2.2)通过指定的字符串参数来创建File类对象,⽽后再与File对象所代表的实际路径建⽴链接创建FileInputStream流对象public FileInputStream(String name) throws FileNotFoundException通过查看源码,发现该构造⽅法等于是在第⼀个构造⽅法的基础上进⾏延伸的,因此规则也和第⼀个构造⽅法⼀致public FileInputStream(String name) throws FileNotFoundException {this(name != null ? new File(name) : null);}2.3)该构造⽅法没有理解---查看api是指使⽤的fdObj⽂件描述符来作为参数,⽂件描述符是指与计算机系统中的⽂件的连接,前⾯两个⽅法的源码中最后都是利⽤⽂件描述符来建⽴连接的public FileInputStream(FileDescriptor fdObj)3)FileInputStream常⽤API3.1)从输⼊流中读取⼀个字节返回int型变量,若到达⽂件末尾,则返回-1public int read() throws IOException理解读取的字节为什么返回int型变量1、⽅法解释中的-1相当于是数据字典告诉调⽤者⽂件已到底,可以结束读取了,这⾥的-1是Int型2、那么当⽂件未到底时,我们读取的是字节,若返回byte类型,那么势必造成同⼀⽅法返回类型不同的情况这是不允许的3、我们读取的字节实际是由8位⼆进制组成,⼆进制⽂件不利于直观查看,可以转成常⽤的⼗进制进⾏展⽰,因此需要把读取的字节从⼆进制转成⼗进制整数,故返回int型4、因此结合以上3点,保证返回类型⼀致以及直观查看的情况,因此该⽅法虽然读取的是字节但返回int型read⽅法读取实例--最后输出内容和字符内容⼀致是123package com.test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class FileStream{/*****/public static void main(String[] args){//建⽴⽂件对象File file=new File("C:\\Users\\Administrator\\Desktop\\1.txt");try{//建⽴链接FileInputStream fileInputStream=new FileInputStream(file);int n=0;StringBuffer sBuffer=new StringBuffer();while (n!=-1) //当n不等于-1,则代表未到末尾{n=fileInputStream.read();//读取⽂件的⼀个字节(8个⼆进制位),并将其由⼆进制转成⼗进制的整数返回char by=(char) n; //转成字符sBuffer.append(by);}System.out.println(sBuffer.toString());}catch (FileNotFoundException e){System.out.println("⽂件不存在或者⽂件不可读或者⽂件是⽬录");}catch (IOException e){System.out.println("读取过程存在异常");}}}3.2)从输⼊流中读取b.length个字节到字节数组中,返回读⼊缓冲区的总字节数,若到达⽂件末尾,则返回-1public int read(byte[] b) throws IOException1. 我们先设定⼀个缓冲区即字节数组⽤于存储从流中读取的字节数据,该数组的长度为N2. 那么就是从流中读取N个字节到字节数组中。
parquet java 读写
parquet java 读写Parquet是一种高效的列式存储格式,广泛应用于大数据处理领域。
在Java中,我们可以使用Parquet库来读取和写入Parquet文件。
本文将介绍如何使用Java进行Parquet文件的读写操作。
Parquet是一种压缩存储格式,它采用了列式存储的方式,将同一列的数据存储在一起,可以提高数据读取的效率。
Parquet文件具有高度压缩和高度可扩展性的特点,适用于大规模数据处理和分析。
在Java中,我们可以使用Apache Parquet库来读取和写入Parquet文件。
首先,我们需要在项目的依赖中添加Parquet库的引用。
可以在Maven或Gradle配置文件中添加以下依赖项:```xml<dependency><groupId>org.apache.parquet</groupId><artifactId>parquet-avro</artifactId><version>1.12.0</version></dependency>```添加依赖后,我们就可以开始使用Parquet库进行读写操作了。
首先,我们需要创建一个ParquetWriter对象来写入Parquet文件。
可以使用以下代码示例来创建一个ParquetWriter对象:```javaConfiguration conf = new Configuration();ParquetWriter<GenericRecord> writer = AvroParquetWriter.<GenericRecord>builder(newPath("output.parquet")).withSchema(schema).withConf(conf).build();```上述代码中,我们首先创建了一个Configuration对象,并将其传递给ParquetWriter的withConf方法。
filereader和filewriter用法
filereader和filewriter用法使用FileReader和FileWriter进行文件读写是Java中常用的操作之一。
FileReader用于读取文本文件的内容,而FileWriter用于向文本文件中写入内容。
下面将逐步介绍这两个类的使用方法。
一、FileReader的使用方法1. 导入FileReader类:首先,需要在Java程序中导入java.io.FileReader类,才能使用它的方法。
可以通过以下代码导入该类:javaimport java.io.FileReader;2. 创建FileReader对象:使用FileReader类的构造方法可以创建FileReader对象。
可以在构造方法中传递文件路径作为参数,示例如下:javaFileReader reader = new FileReader("文件路径");3. 读取文件内容:通过FileReader对象,可以使用read()方法逐字符读取文件内容,直到达到文件末尾。
读取的字符可以存储在一个字符数组或字符流中。
示例如下:javaint data;while((data = reader.read()) != -1) {char ch = (char) data;处理读取到的字符}4. 关闭FileReader对象:在文件读取完成后,需要关闭FileReader对象以释放系统资源。
关闭对象的方法是调用close()方法。
示例如下:javareader.close();二、FileWriter的使用方法1. 导入FileWriter类:同样,需要首先导入java.io.FileWriter类才能使用它的方法。
可以使用以下代码导入该类:javaimport java.io.FileWriter;2. 创建FileWriter对象:使用FileWriter类的构造方法可以创建FileWriter对象。
可以在构造方法中传递文件路径作为参数,示例如下:javaFileWriter writer = new FileWriter("文件路径");3. 写入文件内容:通过FileWriter对象,可以使用write()方法将字符、字符数组或字符串写入文件。
Java8中使用一行代码读取文件
Java8中使⽤⼀⾏代码读取⽂件JDK7中引⼊了新的⽂件操作类java.nio.file.File,它包含了很多有⽤的⽅法来操作⽂件,⽐如检查⽂件是否为隐藏⽂件,或者是检查⽂件是否为只读⽂件。
开发者还可以使⽤Files.readAllBytes(Path)⽅法把整个⽂件读⼊内存,此⽅法返回⼀个字节数组,还可以把结果传递给String的构造器,以便创建字符串输出。
此⽅法确保了当读⼊⽂件的所有字节内容时,⽂件属性是关闭的,否则就会出现IO异常或其它的未检查异常。
这意味着在读⽂件到最后的块内容后,⽆需关闭⽂件。
要注意,此⽅法不适合读取很⼤的⽂件,因为可能存在内存空间不⾜的问题。
开发者还应该明确规定⽂件的字符编码,以避免任异常或解析错误。
如果你想读⼊⽂件作为字符串,那么你还可以使⽤readAllLines(Path path, Charset cs)⽅法,此⽅法与之前的⽅法相似,也是在读完⽂件后⽆需关闭⽂件。
但是它返回的不是字节数组,⽽是字符串数组。
⽽且,Java8重写了此⽅法,⽆需指定字符集,直接使⽤UTF-8编码进⾏字符串转换。
如果你想⼀⾏⼀⾏的读⼊⽂件作为字符串,那么你可以使⽤Files.lines()⽅法,它会从读⼊的⽂件中返回字符串流,并使⽤UTF-8编码把字节转换成字符。
使⽤forEach()⽅法,可以只⽤⼀⾏Java代码实现把⽂件的所有内容输出到控制台,如下⾯第三个代码⽚段。
复制代码代码如下:import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Paths;import java.util.List;public class FileReadingTest {public static void main(String[] args) throws IOException {// Java 7 例⼦// Files.readAllBytes默认以UTF-8编码读⼊⽂件,故⽂件的编码如果不是UTF-8,那么中⽂内容会出现乱字符System.out.println(new String(Files.readAllBytes(Paths.get("D:\\jd.txt"))));// Java 8例⼦List<String> lines = Files.readAllLines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8);StringBuilder sb = new StringBuilder();for(String line : lines){sb.append(line);}String fromFile = sb.toString();System.out.println(fromFile);}}如果使⽤的不是JDK7,⽽是JDK8,那么⼀⾏代码即可完成读⽂件。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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); }}。