java中多种方式读文件,追加文件内容,对文件的各种操作

合集下载

java中多种方式读文件

java中多种方式读文件

java中‎多种方式读‎文件一‎、多种方式‎读文件内容‎。

1、‎按字节读取‎文件内容‎2、按字‎符读取文件‎内容3‎、按行读取‎文件内容‎4、随机‎读取文件内‎容*/‎imp‎o rt j‎a va.i‎o.Buf‎f ered‎R eade‎r;i‎m port‎java‎.io.F‎i le; ‎impo‎r t ja‎v a.io‎.File‎I nput‎S trea‎m;i‎m port‎java‎.io.F‎i leRe‎a der;‎imp‎o rt j‎a va.i‎o.IOE‎x cept‎i on; ‎impo‎r t ja‎v a.io‎.Inpu‎t Stre‎a m;‎i mpor‎t jav‎a.io.‎I nput‎S trea‎m Read‎e r;‎i mpor‎t jav‎a.io.‎R ando‎m Acce‎s sFil‎e;i‎m port‎java‎.io.R‎e ader‎;pu‎b lic ‎c lass‎Read‎F romF‎i le {‎/**‎* 以‎字节为单位‎读取文件,‎常用于读二‎进制文件,‎如图片、声‎音、影像等‎文件。

‎* @pa‎r am f‎i leNa‎m e 文件‎的名*‎/pu‎b lic ‎s tati‎c voi‎d rea‎d File‎B yByt‎e s(St‎r ing ‎f ileN‎a me){‎Fil‎e fil‎e = n‎e w Fi‎l e(fi‎l eNam‎e);‎I nput‎S trea‎m in ‎= nul‎l;t‎r y { ‎Syst‎e m.ou‎t.pri‎n tln(‎"以字节为‎单位读取文‎件内容,一‎次读一个字‎节:");‎// ‎一次读一个‎字节i‎n = n‎e w Fi‎l eInp‎u tStr‎e am(f‎i le);‎int‎temp‎b yte;‎whi‎l e((t‎e mpby‎t e=in‎.read‎()) !‎= -1)‎{Sy‎s tem.‎o ut.w‎r ite(‎t empb‎y te);‎}‎i n.cl‎o se()‎;} ‎c atch‎(IOE‎x cept‎i on e‎) {‎e.pri‎n tSta‎c kTra‎c e();‎ret‎u rn; ‎}t‎r y { ‎Syst‎e m.ou‎t.pri‎n tln(‎"以字节为‎单位读取文‎件内容,一‎次读多个字‎节:");‎//一‎次读多个字‎节by‎t e[] ‎t empb‎y tes ‎= new‎byte‎[100]‎;in‎t byt‎e read‎= 0;‎in ‎= new‎File‎I nput‎S trea‎m(fil‎e Name‎);R‎e adFr‎o mFil‎e.sho‎w Avai‎l able‎B ytes‎(in);‎//读‎入多个字节‎到字节数组‎中,byt‎e read‎为一次读入‎的字节数‎whil‎e ((b‎y tere‎a d = ‎i n.re‎a d(te‎m pbyt‎e s)) ‎!= -1‎){S‎y stem‎.out.‎w rite‎(temp‎b ytes‎, 0, ‎b yter‎e ad);‎}‎} cat‎c h (E‎x cept‎i on e‎1) { ‎e1.p‎r intS‎t ackT‎r ace(‎);}‎fina‎l ly {‎if ‎(in !‎= nul‎l){‎t ry {‎in.‎c lose‎();‎} cat‎c h (I‎O Exce‎p tion‎e1) ‎{} ‎}}‎}‎/**‎*以字符‎为单位读取‎文件,常用‎于读文本,‎数字等类型‎的文件‎* @pa‎r am f‎i leNa‎m e 文件‎名*/‎pub‎l ic s‎t atic‎void‎read‎F ileB‎y Char‎s(Str‎i ng f‎i leNa‎m e){ ‎File‎file‎= ne‎w Fil‎e(fil‎e Name‎);R‎e ader‎read‎e r = ‎n ull;‎try‎{S‎y stem‎.out.‎p rint‎l n("以‎字符为单位‎读取文件内‎容,一次读‎一个字节:‎"); ‎// 一次‎读一个字符‎rea‎d er =‎new ‎I nput‎S trea‎m Read‎e r(ne‎w Fil‎e Inpu‎t Stre‎a m(fi‎l e));‎int‎temp‎c har;‎whi‎l e ((‎t empc‎h ar =‎read‎e r.re‎a d())‎!= -‎1){‎//对于w‎i ndow‎s下,rn‎这两个字符‎在一起时,‎表示一个换‎行。

如何在Java中进行文件读写操作

如何在Java中进行文件读写操作

如何在Java中进行文件读写操作在Java中,我们可以使用各种方式进行文件读写操作。

下面将介绍几种常用的文件读写方式。

一、使用字节流进行文件读写字节流是Java中最基本的IO类,用于读取和写入字节数据。

下面是一个使用字节流进行文件读写的示例代码:```import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class FileReadWrite {public static void main(String[] args) {try {//创建输入流对象FileInputStream in = new FileInputStream("input.txt");//创建输出流对象FileOutputStream out = new FileOutputStream("output.txt"); //读取文件内容byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = in.read(buffer)) != -1) {//写入文件内容out.write(buffer, 0, bytesRead);}//关闭流in.close();out.close();} catch (IOException e) {e.printStackTrace();}}}```上述代码中,通过创建`FileInputStream`对象和`FileOutputStream`对象,实现了将一个文件的内容复制到另一个文件中的功能。

首先,我们创建一个字节数组缓冲区`buffer`,然后使用`read`方法读取文件内容到缓冲区中,接着使用`write`方法将缓冲区的内容写入输出流中。

二、使用字符流进行文件读写字符流在字节流的基础上提供了更高级别的读写功能,可以方便地处理字符数据。

java如何追加写入txt文件

java如何追加写入txt文件

java如何追加写⼊txt⽂件java中,对⽂件进⾏追加内容操作的三种⽅法1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16import java.io.BufferedWriter;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.io.RandomAccessFile;//如果⽂件存在,则追加内容;如果⽂件不存在,则创建⽂件,追加内容的三种⽅法public class AppendContentToFile {@SuppressWarnings("static-access")public static void main(String[] args) {AppendContentToFile a = new AppendContentToFile();a.method1();a.method2("E:\\dd.txt", "222222222222222");a.method3("E:\\dd.txt", "33333333333");}⽅法1:12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20public void method1() {FileWriter fw = null;try{//如果⽂件存在,则追加内容;如果⽂件不存在,则创建⽂件File f=new File("E:\\dd.txt");fw = new FileWriter(f, true);} catch(IOException e) {e.printStackTrace();}PrintWriter pw = new PrintWriter(fw);pw.println("追加内容");pw.flush();try{fw.flush();pw.close();fw.close();} catch(IOException e) {e.printStackTrace();}}⽅法2:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16public static void method2(String file, String conent) { BufferedWriter out = null;try{out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, true)));out.write(conent+"\r\n");} catch(Exception e) {e.printStackTrace();} finally{try{out.close();} catch(IOException e) {e.printStackTrace();}}}⽅法3:12 3public static void method3(String fileName, String content) { try{// 打开⼀个随机访问⽂件流,按读写⽅式4 5 6 7 8 9 10 11 12 13 14 15RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // ⽂件长度,字节数long fileLength = randomFile.length();// 将写⽂件指针移到⽂件尾。

java获取文件内容的方法

java获取文件内容的方法

java获取文件内容的方法【原创实用版3篇】目录(篇1)1.引言2.Java获取文件内容的方法3.方法比较与选择4.结论正文(篇1)一、引言Java 是一种广泛使用的编程语言,它提供了许多用于处理文件和流的功能。

在 Java 中,有多种方法可以获取文件内容,包括使用BufferedReader、Scanner 和 FileReader 等类。

本文将介绍这些方法及其应用场景。

二、Java获取文件内容的方法1.BufferedReader:BufferedReader 是 Java 中最常用的读取文本文件的类之一。

它提供了一个名为 readLine() 的方法,可以逐行读取文件内容。

示例代码如下:```javatry (BufferedReader br = new BufferedReader(newFileReader("file.txt"))) {String line;while ((line = br.readLine()) != null) {// 处理每一行内容}} catch (IOException e) {e.printStackTrace();}```2.Scanner:Scanner 类提供了更简洁的语法来读取输入,包括文件内容。

它使用空格、制表符等分隔符来解析输入,并将其转换为相应的数据类型。

示例代码如下:```javatry (Scanner scanner = new Scanner(new File("file.txt"))) { while (scanner.hasNextLine()) {String line = scanner.nextLine();// 处理每一行内容}} catch (FileNotFoundException e) {e.printStackTrace();}```3.FileReader:FileReader 类用于读取字符流,它返回一个字符数组,其中包含指定文件中的所有字符。

Java中的文件操作

Java中的文件操作

Java中的文件操作Java是一种广泛应用于软件开发的编程语言,它具有跨平台、面向对象的特点,可用于开发各种类型的应用程序。

在Java中,文件操作是一项常见的任务,用于读取、写入和处理文件。

本文将介绍Java中的文件操作相关的内容,包括文件的创建、读取、写入、删除和重命名。

一、文件的创建在Java中,可以使用File类来创建文件对象,然后通过文件对象的方法进行文件的创建。

具体的步骤如下:1. 导入File类```javaimport java.io.File;```2. 创建文件对象```javaFile file = new File("filepath/filename");```其中,"filepath/filename"是文件的路径和名称,可以是绝对路径或相对路径。

3. 创建文件```javafile.createNewFile();```该方法会在指定路径下创建一个空文件。

二、文件的读取Java提供了多种方式用于读取文件的内容,以下介绍两种常用的方法:1. 使用InputStream读取文件```javaimport java.io.FileInputStream;import java.io.InputStream;public class ReadFileExample {public static void main(String[] args) throws Exception {File file = new File("filepath/filename");InputStream inputStream = new FileInputStream(file);int data = inputStream.read();while (data != -1) {System.out.print((char) data);data = inputStream.read();}inputStream.close();}}```该方法使用FileInputStream来创建输入流,通过循环读取流中的数据并转换为字符输出。

java读取文件的几种方式和通过url获取文件

java读取文件的几种方式和通过url获取文件

java读取⽂件的⼏种⽅式和通过url获取⽂件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读取文件内容的六种方法

Java读取文件内容的六种方法

Java读取⽂件内容的六种⽅法1.Scanner第⼀种⽅式是Scanner,从JDK1.5开始提供的API,特点是可以按⾏读取、按分割符去读取⽂件数据,既可以读取String类型,也可以读取Int类型、Long类型等基础数据类型的数据。

@Testvoid testReadFile1() throws IOException {//⽂件内容:Hello World|Hello ZimugString fileName = "D:\\data\\test\\newFile4.txt";try (Scanner sc = new Scanner(new FileReader(fileName))) {while (sc.hasNextLine()) { //按⾏读取字符串String line = sc.nextLine();System.out.println(line);}}try (Scanner sc = new Scanner(new FileReader(fileName))) {eDelimiter("\\|"); //分隔符while (sc.hasNext()) { //按分隔符读取字符串String str = sc.next();System.out.println(str);}}//sc.hasNextInt() 、hasNextFloat() 、基础数据类型等等等等。

//⽂件内容:1|2fileName = "D:\\data\\test\\newFile5.txt";try (Scanner sc = new Scanner(new FileReader(fileName))) {eDelimiter("\\|"); //分隔符while (sc.hasNextInt()) { //按分隔符读取Intint intValue = sc.nextInt();System.out.println(intValue);}}}上⾯的⽅法输出结果如下:Hello World|Hello ZimugHello WorldHello Zimug122.Files.lines (Java 8)如果你是需要按⾏去处理数据⽂件的内容,这种⽅式是我推荐⼤家去使⽤的⼀种⽅式,代码简洁,使⽤java 8的Stream流将⽂件读取与⽂件处理有机融合。

Java文件操作:掌握文件读写和目录操作的方法

Java文件操作:掌握文件读写和目录操作的方法

Java文件操作:掌握文件读写和目录操作的方法引言:在Java编程中,文件操作是一项非常重要的技能。

无论是读取文件内容、写入文件数据,还是对目录进行操作,掌握文件操作的方法对于开发者来说都是至关重要的。

本文将介绍Java中文件读写和目录操作的方法,帮助读者更好地掌握这一技能。

一、文件读操作:在Java中,文件读操作可以通过FileInputStream和BufferedReader来实现。

下面是一个简单的示例代码:```javaimport java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;public class FileReadExample {public static void main(String[] args) {try {File file = new File("example.txt");FileInputStream fileInputStream = new FileInputStream(file);InputStreamReader inputStreamReader = newInputStreamReader(fileInputStream);BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String line;while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}bufferedReader.close();} catch (Exception e) {e.printStackTrace();}}}```在上面的示例代码中,首先创建了一个File对象,指定了要读取的文件路径。

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

java中多种方式读文件,追加文件内容,对文件的各种操作一、多种方式读文件内容。

1、按字节读取文件内容2、按字符读取文件内容3、按行读取文件内容4、随机读取文件内容2008-5-7 09:48 我思念的城市import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.RandomAccessFile;import java.io.Reader;public class ReadFromFile {/*** 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

* @param fileName 文件的名*/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) {}}}}/*** 以字符为单位读取文件,常用于读文本,数字等类型的文件* @param fileName 文件名*/2008-5-7 09:52 我思念的城市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) {}}}}/*** 以行为单位读取文件,常用于读面向行的格式化文件* @param fileName 文件名*/2008-5-7 09:53 我思念的城市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) {}}}}/*** 随机读取文件内容* @param fileName 文件名*/2008-5-7 09:55 我思念的城市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) {}}}}/*** 显示输入流中还剩的字节数* @param in*/2008-5-7 09:55 我思念的城市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);}}2008-5-7 09:56 我思念的城市二、将内容追加到文件尾部import java.io.FileWriter;import java.io.IOException;import java.io.RandomAccessFile;/*** 将内容追加到文件尾部*/public class AppendToFile {/*** A方法追加文件:使用RandomAccessFile* @param fileName 文件名* @param content 追加的内容*/public static void appendMethodA(String fileName, String content){ try {// 打开一个随机访问文件流,按读写方式RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");// 文件长度,字节数long fileLength = randomFile.length();//将写文件指针移到文件尾。

相关文档
最新文档