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中进行数据的持久化和读取操作

如何在Java中进行数据的持久化和读取操作

如何在Java中进行数据的持久化和读取操作数据的持久化是指将程序中的数据存储在持久存储介质中(如文件、数据库等)以便下次程序运行时能够重新读取和使用。

在Java中,数据的持久化和读取操作可以通过文件操作、数据库操作、序列化和反序列化等方式实现。

本文将重点介绍在Java中进行数据的持久化和读取操作的几种方法。

一、文件操作1.1文件写入在Java中进行文件数据的持久化操作可以使用FileOutputStream 或者BufferedWriter等类来实现。

通过FileOutputStream类,可以将数据以字节的形式写入文件,示例代码如下:```javatry {String data = "Hello, World!";FileOutputStream fos = new FileOutputStream("data.txt");fos.write(data.getBytes());fos.close();} catch (IOException e) {e.printStackTrace();}```上述代码中,首先定义了一个字符串数据并赋值给data变量,然后通过FileOutputStream类打开文件输出流,并将字符串数据以字节形式写入文件中,最后关闭文件输出流。

1.2文件读取使用FileInputStream或者BufferedReader类可以实现对文件数据的读取操作。

示例代码如下:```javatry {FileInputStream fis = new FileInputStream("data.txt");int content;while ((content = fis.read()) != -1) {System.out.print((char) content);}fis.close();} catch (IOException e) {e.printStackTrace();}```上述代码中,首先使用FileInputStream类打开文件输入流,并定义一个整型变量content用于存储读取的字节数据。

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对CSV文件进行读写操作

用Java对CSV文件进行读写操作

⽤Java对CSV⽂件进⾏读写操作需要jar包:javacsv-2.0.jar读操作// 读取csv⽂件的内容public static ArrayList<String> readCsv(String filepath) {File csv = new File(filepath); // CSV⽂件路径csv.setReadable(true);//设置可读csv.setWritable(true);//设置可写BufferedReader br = null;try {br = new BufferedReader(new FileReader(csv));} catch (FileNotFoundException e) {e.printStackTrace();}String line = "";String everyLine = "";ArrayList<String> allString = new ArrayList<>();try {while ((line = br.readLine()) != null) // 读取到的内容给line变量{everyLine = line;System.out.println(everyLine);allString.add(everyLine);}System.out.println("csv表格中所有⾏数:" + allString.size());} catch (IOException e) {e.printStackTrace();}return allString;}写操作public void writeCSV(String path) {String csvFilePath = path;try {// 创建CSV写对象例如:CsvWriter(⽂件路径,分隔符,编码格式);CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));// 写内容String[] headers = {"FileName","FileSize","FileMD5"};csvWriter.writeRecord(headers);for(int i=0;i<writearraylist.size();i++){String[] writeLine=writearraylist.get(i).split(",");System.out.println(writeLine);csvWriter.writeRecord(writeLine);}csvWriter.close();System.out.println("--------CSV⽂件已经写⼊--------");} catch (IOException e) {e.printStackTrace();}}。

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读写CSV文件的两种方法

java读写CSV文件的两种方法

java读写CSV⽂件的两种⽅法---------------------------------------------------------⼩路原创,转载请注明出处!------------------------------------------起初,我⾃⼰连什么叫CSV⽂件都不知道,这个问题是来⾃⼀个⽹友的问题,他要我帮他做⼀个对csv⽂件数据的操作的题⽬。

要求:如果原来数据是“江苏省南京市南京街……”换成“江苏省南京市 CSV⽂件简介:Comma Separated Values,简称CSV,即逗号分隔值,是⼀种纯⽂本格式,⽤来存储数据。

在CSV中,数据的字段由逗号分开。

CSV⽂件是⼀个计算机数据⽂件⽤于执⾏审判和真正的组织⼯具,逗号分隔的清单下⾯是最开始写的⽐较累赘的代码:package test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class OperateCSVfile {public static void main(String[] args){String [] str = {"省","市","区","街","路","⾥","幢","村","室","园","苑","巷","号"};File inFile = new File("C://in.csv"); // 读取的CSV⽂件File outFile = new File("C://out.csv");//写出的CSV⽂件String inString = "";String tmpString = "";try {BufferedReader reader = new BufferedReader(new FileReader(inFile));BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));while((inString = reader.readLine())!= null){char [] c = inString.toCharArray();String [] value = new String[c.length];String result = "";for(int i = 0;i < c.length;i++){value[i] = String.valueOf(c[i]);for(int j = 0;j < str.length;j++){if(value[i].equals(str[j])){String tmp = value[i];value[i] = "," + tmp + ",";}}result += value[i];}writer.write(inString);writer.newLine();}reader.close();writer.close();} catch (FileNotFoundException ex) {System.out.println("没找到⽂件!");} catch (IOException ex) {System.out.println("读写⽂件出错!");}}}利⽤String类的replace()⽅法之后的代码简化为;package test;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class OperateCSVfile {public static void main(String[] args){String [] str = {"省","市","区","街","路","⾥","幢","村","室","园","苑","巷","号"};File inFile = new File("C://in.csv"); // 读取的CSV⽂件File outFile = new File("C://out.csv");//写出的CSV⽂件String inString = "";String tmpString = "";try {BufferedReader reader = new BufferedReader(new FileReader(inFile));BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));while((inString = reader.readLine())!= null){for(int i = 0;i<str.length;i++){tmpString = inString.replace(str[i], "," + str[i] + ",");inString = tmpString;}writer.write(inString);writer.newLine();}reader.close();writer.close();} catch (FileNotFoundException ex) {System.out.println("没找到⽂件!");} catch (IOException ex) {System.out.println("读写⽂件出错!");}}}效果图;之后我⼜在⽹上查了⼀下资料,发现java有专门操作CSV⽂件的类和⽅法。

  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(fi le));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(fi leName));// 读入多个字符到字符数组中,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);}}5、将内容追加到文件尾部public class AppendToFile {/*** A方法追加文件:使用RandomAccessFile*/public static void appendMethodA(String fileName, String co ntent) {try {// 打开一个随机访问文件流,按读写方式RandomAccessFile randomFile = new RandomAccessFile (fileName, "rw");// 文件长度,字节数long fileLength = randomFile.length();//将写文件指针移到文件尾。

randomFile.seek(fileLength);randomFile.writeBytes(content);randomFile.close();} catch (IOException e) {e.printStackTrace();}}/*** B方法追加文件:使用FileWriter*/public static void appendMethodB(String fileName, String co ntent) {try {//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件FileWriter writer = new FileWriter(fileName, true);writer.write(content);writer.close();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {String fileName = "C:/temp/newTemp.txt";String content = "new append!";//按方法A追加文件AppendToFile.appendMethodA(fileName, content);AppendToFile.appendMethodA(fileName, "append end. \n ");//显示文件内容ReadFromFile.readFileByLines(fileName);//按方法B追加文件AppendToFile.appendMethodB(fileName, content);AppendToFile.appendMethodB(fileName, "append end. \n" );//显示文件内容ReadFromFile.readFileByLines(fileName);}}。

相关文档
最新文档