Java 对文件读写操作

合集下载

java程序读取服务器端数据文件的方法

java程序读取服务器端数据文件的方法

java程序读取服务器端数据文件的方法
1. 使用Java IO流读取服务器端文件:
使用Java IO流可以读取服务器端文件,具体步骤如下:
(1)使用URL类的openStream()方法获取URL对象的输入流;
(2)使用BufferedReader类的readLine()方法读取文件内容;
(3)使用String类的split()方法将读取的内容按照指定的分隔符分割为字符串数组;
(4)使用Arrays类的toString()方法将字符串数组转换为字符串;
(5)使用String类的replace()方法替换掉特殊字符;
(6)使用String类的split()方法将字符串按照指定的分隔符分割为字符串数组;
(7)使用for循环遍历字符串数组,将每个字符串元素添加到ArrayList中;
(8)将ArrayList转换为字符串数组,并返回。

2. 使用Java NIO读取服务器端文件:
使用Java NIO可以读取服务器端文件,具体步骤如下:
(1)使用Paths类的get()方法获取服务器端文件的路径;
(2)使用Files类的readAllBytes()方法读取文件的所有字节;
(3)使用String类的split()方法将读取的内容按照指定的分隔符分割为字符串数组;
(4)使用for循环遍历字符串数组,将每个字符串元素添加到ArrayList中;
(5)将ArrayList转换为字符串数组,并返回。

java中easyexsl的用法

java中easyexsl的用法

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

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

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

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

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

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

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

如何在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 顺序读写文件的原理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从文件中读取数据并存入对象中的方法

java从文件中读取数据并存入对象中的方法

一、概述在软件开发中,经常会遇到需要从文件中读取数据并存入对象中的情况,尤其是在使用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的RandomAccessFile对文件内容进行读写

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

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

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

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

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

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

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

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

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

Java 对文件进行读写操作的例子很多,让初学者感到十分困惑,我觉得有必要将各种方法进行
一次分析,归类,理清不同方法之间的异同点。

一.在JDK 1.0 中,通常是用InputStream & OutputStream 这两个基类来进行读写操作的。

InputStream 中的FileInputStream 类似一个文件句柄,通过它来对文件进行操作,类似的,在
OutputStream 中我们有FileOutputStream 这个对象。

用FileInputStream 来读取数据的常用方法是:
FileInputStream fstream = new FileInputStream(args[0]);
DataInputStream in = new DataInputStream(fstream);
用in.readLine() 来得到数据,然后用in.close() 关闭输入流。

完整代码见Example 1。

用FileOutputStream 来写入数据的常用方法是:
FileOutputStream out out = new FileOutputStream("myfile.txt");
PrintStream p = new PrintStream( out );
用p.println() 来写入数据,然后用p.close() 关闭输入。

完整代码见Example 2。

二.在JDK 1.1中,支持两个新的对象Reader & Writer,它们只能用来对文本文件进行操作,而
JDK1.1中的InputStream & OutputStream 可以对文本文件或二进制文件进行操作。

用FileReader 来读取文件的常用方法是:
FileReader fr = new FileReader("mydata.txt");
BufferedReader br = new BufferedReader(fr);
用br.readLing() 来读出数据,然后用br.close() 关闭缓存,用fr.close() 关闭文件。

完整代码见Example 3。

用FileWriter 来写入文件的常用方法是:
FileWriter fw = new FileWriter("mydata.txt");
PrintWriter out = new PrintWriter(fw);
在用out.print 或out.println 来往文件中写入数据,out.print 和out.println的唯一区别是后者写
入数据或会自动开一新行。

写完后要记得用out.close() 关闭输出,用fw.close() 关闭文件。

完整代码见Example 4。

-------------------------------------------------------------- following is the source code of examples------------------------------------------------------
Example 1:
// FileInputDemo
// Demonstrates FileInputStream and DataInputStream
import java.io.*;
class FileInputDemo {
public static void main(String args[]) {
// args.length is equivalent to argc in C
if (args.length == 1) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(args[0]);
// Convert our input stream to a DataInputStream
DataInputStream in = new DataInputStream(fstream);
// Continue to read lines while there are still some left to read while (in.available() !=0) {
// Print file line to screen
System.out.println (in.readLine());
}
in.close();
} catch (Exception e) {
System.err.println("File input error");
}
}
else
System.out.println("Invalid parameters");
}
}
Example 2:
// FileOutputDemo
// Demonstration of FileOutputStream and PrintStream classes import java.io.*;
class FileOutputDemo
{
public static void main(String args[]) {
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try {
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.println ("This is written to a file");
p.close();
} catch (Exception e) {
System.err.println ("Error writing to file");
}
}
}
Example 3:
// FileReadTest.java
// User FileReader in JDK1.1 to read a file
import java.io.*;
class FileReadTest {
public static void main (String[] args) {
FileReadTest t = new FileReadTest();
t.readMyFile();
}
void readMyFile() {
String record = null;
int recCount = 0;
try {
FileReader fr = new FileReader("mydata.txt");
BufferedReader br = new BufferedReader(fr);
record = new String();
while ((record = br.readLine()) != null) {
recCount++;
System.out.println(recCount + ": " + record);
}
br.close();
fr.close();
} catch (IOException e) {
System.out.println("Uh oh,got an IOException error!");
e.printStackTrace();
}
}
}
Example 4:
// FileWriteTest.java
// User FileWriter in JDK1.1 to writer a file
import java.io.*;
class FileWriteTest {
public static void main (String[] args) {
FileWriteTest t = new FileWriteTest();
t.WriteMyFile();
}
void WriteMyFile() {
try {
FileWriter fw = new FileWriter("mydata.txt");
PrintWriter out = new PrintWriter(fw);
out.print(“hi,this will be wirte into the file!”);
out.close();
fw.close();
} catch (IOException e) {
System.out.println("Uh oh,got an IOException error!");
e.printStackTrace();
}
}
}。

相关文档
最新文档