JAVA中文件的读写
- 格式:pdf
- 大小:72.40 KB
- 文档页数:4
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⼀次性读取或者写⼊⽂本⽂件所有内容⼀次性读取⽂本⽂件所有内容我们做⽂本处理的时候的最常⽤的就是读写⽂件了,尤其是读取⽂件,不论是什么⽂件,我都倾向于⼀次性将⽂本的原始内容直接读取到内存中再做处理,当然,这需要你有⼀台⼤内存的机器,内存不够者……可以⼀次读取少部分内容,分多次读取。
读取⽂件效率最快的⽅法就是⼀次全读进来,很多⼈⽤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提供了多种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读取文件的方法1. 使用File类和Scanner类读取文件Java中可以使用File类和Scanner类来读取文件中的数据。
首先通过File类创建文件对象,然后通过Scanner类来读取文件中的内容。
以下是一个简单的示例代码:```javaimport java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class ReadFromFile {public static void m本人n(String[] args) {try {File file = new File("data.txt");Scanner scanner = new Scanner(file);while (scanner.hasNextLine()) {String data = scanner.nextLine();System.out.println(data);}scanner.close();} catch (FileNotFoundException e) {System.out.println("File not found");e.printStackTrace();}}}```2. 使用BufferedReader类读取文件除了Scanner类,还可以使用BufferedReader类来读取文件中的数据。
与Scanner类不同,BufferedReader类提供了更高效的读取方式。
以下是一个使用BufferedReader类读取文件的示例代码:```javaimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ReadFromFile {public static void m本人n(String[] args) {try {BufferedReader reader = new BufferedReader(new FileReader("data.txt"));String line = reader.readLine();while (line != null) {System.out.println(line);line = reader.readLine();}reader.close();} catch (IOException e) {System.out.println("IO Exception");e.printStackTrace();}}}```以上是使用Java读取文件的基本方法,开发者可以根据实际需求选择合适的方式来读取文件中的数据。
java读写word文档完美解决方案Java读写Word文档:完美解决方案Word文档是一种广泛使用的文件格式,用于创建和编辑文本文档。
在Java编程中,读写Word文档是一个常见的需求。
本文将介绍一种完美解决方案,帮助您在Java中实现对Word文档的读写操作。
一、引入依赖要在Java中读写Word文档,我们需要使用Apache POI库。
Apache POI是一个Java类库,可用于读取和编写Microsoft Office文件格式,包括Word文档。
在您的Java项目中,您需要将以下依赖项添加到您的构建文件中,以便使用Apache POI库:```java<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>```二、读取Word文档要读取一个Word文档,您可以使用Apache POI提供的XWPFDocument类。
以下是一个简单的示例代码,演示如何使用XWPFDocument读取Word文档:```javaimport ermodel.XWPFDocument;import org.apache.poi.xwpf.extractor.XWPFWordExtractor;import java.io.FileInputStream;import java.io.IOException;public class ReadWordDocument {public static void main(String[] args) {try {FileInputStream fis = newFileInputStream("path/to/your/word/document.docx");XWPFDocument document = new XWPFDocument(fis);XWPFWordExtractor extractor = new XWPFWordExtractor(document);String content = extractor.getText();System.out.println(content);fis.close();} catch (IOException e) {e.printStackTrace();}}}```在上面的代码中,您需要将"path/to/your/word/document.docx"替换为您实际的Word文档路径。
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 ;}}这样修改了指定的内容,⽽且还保证了⽂件的原格式,但有个问题是⽂件的注释会丢失;。
在MacOS上使用Java实现文件读写操作在MacOS系统上,使用Java语言进行文件读写操作是一种常见的需求。
Java提供了丰富的API和库,使得文件处理变得简单而高效。
本文将介绍如何在MacOS上使用Java实现文件读写操作,包括文件的创建、写入、读取和删除等操作。
1. 文件的创建在Java中,可以使用File类来表示文件或目录,并通过该类的方法来创建文件。
下面是一个简单的示例代码,演示了如何在MacOS上创建一个新的文件:示例代码star:编程语言:javaimport java.io.File;import java.io.IOException;public class CreateFileExample {public static void main(String[] args) {File file = new File("example.txt");try {if (file.createNewFile()) {System.out.println("File created: " + file.getName());} else {System.out.println("File already exists.");}} catch (IOException e) {System.out.println("An error occurred.");e.printStackTrace();}}}示例代码end运行以上代码后,将在当前目录下创建一个名为example.txt的文件。
2. 文件的写入要向文件中写入数据,可以使用FileWriter类。
下面是一个简单的示例代码,演示了如何在MacOS上向文件中写入内容:示例代码star:编程语言:javaimport java.io.FileWriter;import java.io.IOException;public class WriteToFileExample {public static void main(String[] args) {try {FileWriter writer = newFileWriter("example.txt");writer.write("Hello, World!");writer.close();System.out.println("Successfully wrote to the file.");} catch (IOException e) {System.out.println("An error occurred.");e.printStackTrace();}}}示例代码end运行以上代码后,example.txt文件中将会写入”Hello, World!“这行内容。