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("您输入的有误,请重新输入!");}}}}}。
- 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); }}。