java中多种方式读文件,追加文件内容,对文件的各种操作
- 格式:doc
- 大小:50.00 KB
- 文档页数:14
java中多种方式读文件一、多种方式读文件内容。
1、按字节读取文件内容2、按字符读取文件内容3、按行读取文件内容4、随机读取文件内容*/impo rt ja va.io.Buff eredR eader;im portjava.io.Fi le; impor t jav a.io.FileI nputS tream;im portjava.io.Fi leRea der;impo rt ja va.io.IOEx cepti on; impor t jav a.io.Input Strea m;i mport java.io.I nputS tream Reade r;i mport java.io.R andom Acces sFile;im portjava.io.Re ader;pub lic c lassReadF romFi le {/*** 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
* @par am fi leNam e 文件的名*/pub lic s tatic void read FileB yByte s(Str ing f ileNa me){File file = ne w Fil e(fil eName);I nputS tream in = null;tr y { Syste m.out.prin tln("以字节为单位读取文件内容,一次读一个字节:");// 一次读一个字节in = ne w Fil eInpu tStre am(fi le);inttempb yte;whil e((te mpbyt e=in.read()) != -1){Sys tem.o ut.wr ite(t empby te);}i n.clo se();} c atch(IOEx cepti on e) {e.prin tStac kTrac e();retu rn; }tr y { Syste m.out.prin tln("以字节为单位读取文件内容,一次读多个字节:");//一次读多个字节byt e[] t empby tes = newbyte[100];int byte read= 0;in = newFileI nputS tream(file Name);Re adFro mFile.show Avail ableB ytes(in);//读入多个字节到字节数组中,byte read为一次读入的字节数while ((by terea d = i n.rea d(tem pbyte s)) != -1){Sy stem.out.w rite(tempb ytes, 0, b ytere ad);}} catc h (Ex cepti on e1) { e1.pr intSt ackTr ace();}final ly {if (in != null){t ry {in.c lose();} catc h (IO Excep tione1) {} }}}/***以字符为单位读取文件,常用于读文本,数字等类型的文件* @par am fi leNam e 文件名*/publ ic st aticvoidreadF ileBy Chars(Stri ng fi leNam e){ Filefile= new File(file Name);Re aderreade r = n ull;try{Sy stem.out.p rintl n("以字符为单位读取文件内容,一次读一个字节:"); // 一次读一个字符read er =new I nputS tream Reade r(new File Input Strea m(fil e));inttempc har;whil e ((t empch ar =reade r.rea d())!= -1){//对于wi ndows下,rn这两个字符在一起时,表示一个换行。
如何在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中,对⽂件进⾏追加内容操作的三种⽅法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获取文件内容的方法【原创实用版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中,可以使用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获取⽂件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读取⽂件内容的六种⽅法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中,文件读操作可以通过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对象,指定了要读取的文件路径。
转:JAVA读写文件大全,将内容追加到文件尾部1、java读写文件大全最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中write(char[] ch,int off,intlength),flush()和close()方法为抽象方法,Reader中read(char[] ch,int off,int length)和close()方法是抽象方法。
子类应该分别实现他们。
当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStreamReader和BufferedReader。
其中最重要的类是InputStreamReader,它是字节转换为字符的桥梁。
你可以在构造器重指定编码的方式,如果不指定的话将采用底层操作系统的默认编码方式,例如GBK等。
当使用FileReader读取文件的时候。
package com.thread.test;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 {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下,rn这两个字符在一起时,表示一个换行。
Java读取文本文件的方法在Java中,读取文本文件是一项常见的任务。
通过使用Java的输入输出库,我们可以轻松地读取文本文件的内容并对其进行处理。
本文将介绍几种常用的Java读取文本文件的方法,包括使用FileReader、BufferedReader和Scanner等类。
让我们逐一了解这些方法。
使用FileReader类FileReader类是Java IO库中用于读取字符文件的类。
以下是使用FileReader类读取文本文件的步骤:1.创建一个FileReader对象,将文件路径作为参数传递给它。
FileReader fileReader = new FileReader("path/to/file.txt");2.创建一个字符数组来存储从文件中读取的内容。
char[] buffer = new char[1024];3.使用FileReader的read()方法读取文件内容,并将其存储在字符数组中。
int length = fileReader.read(buffer);4.使用String的构造函数将字符数组转换为字符串。
String content = new String(buffer, 0, length);5.关闭FileReader对象。
fileReader.close();以下是一个完整的示例代码:import java.io.FileReader;import java.io.IOException;public class FileReaderExample {public static void main(String[] args) {try {FileReader fileReader = new FileReader("path/to/file.txt");char[] buffer = new char[1024];int length = fileReader.read(buffer);String content = new String(buffer, 0, length);fileReader.close();System.out.println(content);} catch (IOException e) {e.printStackTrace();}}}使用BufferedReader类BufferedReader类是Java IO库中用于读取文本文件的高效类。
java获取文件内容的方法Java是一种功能强大的编程语言,它提供了丰富的API(应用程序接口)来操作文件和读取文件内容。
在本文中,我们将介绍几种常用的方法来获取文件内容。
1. 使用File类Java中的File类提供了许多方法来操作文件。
要获取文件内容,我们可以使用File类的方法之一——`readLines()`。
这个方法会将文件的内容读取到一个字符串列表中,每一行作为一个元素。
```javaimport java.io.File;import java.io.IOException;import java.nio.file.Files;import java.util.List;public class ReadFileExample {public static void main(String[] args) {File file = new File("path/to/file.txt");try {List<String> lines = Files.readAllLines(file.toPath());for (String line : lines) {System.out.println(line);}} catch (IOException e) {e.printStackTrace();}}}```在上面的示例中,我们首先创建一个File对象,指定要读取的文件的路径。
然后,我们使用Files类的`readAllLines()`方法将文件内容读取到一个字符串列表中。
最后,我们使用循环遍历这个列表,并输出每一行的内容。
2. 使用BufferedReader类除了使用File类,我们还可以使用BufferedReader类来读取文件内容。
这个类提供了一种更高效的方式来逐行读取文件。
```javaimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ReadFileExample {public static void main(String[] args) {String filePath = "path/to/file.txt";try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {String line;while ((line = reader.readLine()) != null) {System.out.println(line);}} catch (IOException e) {e.printStackTrace();}}}```在上面的示例中,我们首先创建一个BufferedReader对象,使用FileReader来读取文件。
Java读取⽂本⽂件的各种⽅法⽬录1、⽅法⽅法⼀、使⽤BufferedReader类⽅法⼆、使⽤ FileReader 类⽅法三、使⽤ Scanner 类⽅法四、读取列表中的整个⽂件2、语法⽅法五、将⽂本⽂件读取为字符串前⾔:有多种写⼊和读取⽂本⽂件的⽅法。
这在处理许多应⽤程序时是必需的。
在Java 中有多种⽅法可以读取纯⽂本⽂件,例如你可以使⽤FileReader、BufferedReader或Scanner来读取⽂本⽂件。
每个实⽤程序都提供了⼀些特殊的东西,例如BufferedReader 为快速读取提供数据缓冲,⽽Scanner 提供解析能⼒。
1、⽅法使⽤BufferedReader 类使⽤Scanner 类使⽤⽂件阅读器类读取列表中的整个⽂件将⽂本⽂件读取为字符串我们还可以同时使⽤BufferReader 和Scanner在Java 中逐⾏读取⽂本⽂件。
然后Java SE 8引⼊了另⼀个Stream类java.util.stream.Stream,它提供了⼀种惰性且更有效的⽅式来读取⽂件。
让我们更深⼊地讨论上述每个⽅法,最重要的是通过⼀个⼲净的Java 程序实现它们。
⽅法⼀、使⽤BufferedReader类此⽅法从字符输⼊流中读取⽂本。
它确实缓冲以有效读取字符、数组和⾏。
可以指定缓冲区⼤⼩,也可以使⽤默认⼤⼩。
对于⼤多数⽤途,默认值⾜够⼤。
通常,Reader 发出的每个读取请求都会导致对底层字符或字节流发出相应的读取请求。
因此,建议将BufferedReader 包装在任何 read() 操作可能代价⾼昂的Reader 周围,例如FileReaders和InputStreamReaders,如下所⽰:BufferedReader in = new BufferedReader(Reader in, int size);例⼦:import java.io.*;public class HY {public static void main(String[] args) throws Exception{File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");BufferedReader br= new BufferedReader(new FileReader(file));String st;while ((st = br.readLine()) != null)System.out.println(st);}}输出:如果你想学习编程可以参考海拥的博客⽅法⼆、使⽤ FileReader 类读取字符⽂件的便利类。
一、多种方式读文件内容。
1、按字节读取文件内容2、按字符读取文件内容3、按行读取文件内容4、随机读取文件内容Java代码1.import java。
io。
BufferedReader;2.import java.io.File;3.import java。
io。
FileInputStream;4.import java。
io.FileReader;5.import java。
io。
IOException;6.import java.io。
InputStream;7.import java.io。
InputStreamReader;8.import java.io。
RandomAccessFile;9.import java。
io。
Reader;10.public class ReadFromFile {11./**12.*以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
13. * @param fileName 文件的名14.*/15.public static void readFileByBytes(String fileName){16. File file = new File(fileName);17. InputStream in = null;18.try{19. System。
out.println(”以字节为单位读取文件内容,一次读一个字节:”);20.// 一次读一个字节21. in = new FileInputStream(file);22.int tempbyte;23.while((tempbyte=in。
read()) != -1){24. System。
out。
write(tempbyte);25. }26. in。
close();27. } catch(IOException e){28. e.printStackTrace();29.return;30.}31.try {32. System。
java⽂件创建、删除、读取、写⼊操作⼤全⼀.获得控制台⽤户输⼊的信息public String getInputMessage() throws IOException...{System.out.println("请输⼊您的命令∶");byte buffer[]=new byte[1024];int count=System.in.read(buffer);char[] ch=new char[count-2];//最后两位为结束符,删去不要for(int i=0;i<count-2;i++)ch[i]=(char)buffer[i];String str=new String(ch);return str;}可以返回⽤户输⼊的信息,不⾜之处在于不⽀持中⽂输⼊,有待进⼀步改进。
⼆.复制⽂件1.以⽂件流的⽅式复制⽂件public void copyFile(String src,String dest) throws IOException...{FileInputStream in=new FileInputStream(src);File file=new File(dest);if(!file.exists())file.createNewFile();FileOutputStream out=new FileOutputStream(file);int c;byte buffer[]=new byte[1024];while((c=in.read(buffer))!=-1)...{for(int i=0;i<c;i++)out.write(buffer[i]);}in.close();out.close();}该⽅法经过测试,⽀持中⽂处理,并且可以复制多种类型,⽐如txt,xml,jpg,doc等多种格式三.写⽂件1.利⽤PrintStream写⽂件public void PrintStreamDemo()...{try ...{FileOutputStream out=new FileOutputStream("D:/test.txt");PrintStream p=new PrintStream(out);for(int i=0;i<10;i++)p.println("This is "+i+" line");} catch (FileNotFoundException e) ...{e.printStackTrace();}}2.利⽤StringBuffer写⽂件public void StringBufferDemo() throws IOException......{File file=new File("/root/sms.log");if(!file.exists())file.createNewFile();FileOutputStream out=new FileOutputStream(file,true);for(int i=0;i<10000;i++)......{StringBuffer sb=new StringBuffer();sb.append("这是第"+i+"⾏:前⾯介绍的各种⽅法都不关⽤,为什么总是奇怪的问题 ");out.write(sb.toString().getBytes("utf-8"));}out.close();}该⽅法可以设定使⽤何种编码,有效解决中⽂问题。
Java增、删、改、查txt⽂件1.txtzhang,f3d8071f8f789df766588469ecc6b1f5;package readtext;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;publicclass ReadText {/*** @param args* @throws IOException*/publicstaticvoid main(String[] args) throws IOException {String FileName="C:/1.txt";File f=new File(FileName);char act='u';String UserName="zhang";String SID="f3d8071f8f789df766588469ecc6b1f5";switch(act){case'c':ReadText.CreateTxt(f);break;case'r':ReadText.ReadTxt(f);break;case'w':ReadText.WriteTxt(f, SID,UserName);break;case'd':ReadText.DeleteTxt(f);break;case'u':ReadText.UpdateTxt(f, SID);break;}}//新建⽂件publicstaticvoid CreateTxt(File f){if(f.exists()){System.out.println("⽂件已存在");}else{try{// 新建text⽂件f.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//删除⽂件publicstaticvoid DeleteTxt(File f){if(f.exists()){f.delete();System.out.println("⽂件delete");}else{System.out.println("⽂件不存在");}}//读⽂件publicstaticvoid ReadTxt(File f) throws IOException{String read;String readStr ="";if(f.exists()){BufferedReader br =new BufferedReader(new FileReader(f));while ((read = br.readLine()) !=null) {readStr = readStr + read;}br.close();System.out.println("⽂件内容是:"+"\r\n"+ readStr);}else{System.out.println("⽂件不存在!");}}publicstaticint CheckUser(File f,String SID) throws IOException{int isOk=0;String read;String readStr ="";if(!f.exists()){f.createNewFile();}BufferedReader br =new BufferedReader(new FileReader(f));while ((read = br.readLine()) !=null) {readStr = readStr + read;}br.close();if(readStr==""||readStr==null){isOk=1;System.out.println("null or ''");}else{String[] str1=readStr.split(";");for(int i=0;i<str1.length;i++){String[] str_sid=str1[i].split(",");//System.out.println(str1[i]);if(str_sid[1].equals(SID)){System.out.println("SID--------"+SID);System.out.println("str_sid[1]------"+str_sid[1]);isOk=0;}else{isOk=1;}}}return isOk;}//写⽂件publicstaticvoid WriteTxt(File f,String SID,String UserName) throws IOException{ String read;String readStr ="";if(!f.exists()){f.createNewFile();}BufferedReader br =new BufferedReader(new FileReader(f));while ((read = br.readLine()) !=null) {readStr = readStr + read;}br.close();int l=CheckUser(f, SID);if(l==1){PrintWriter bf=new PrintWriter(new FileWriter(f));String newstr=UserName+","+SID+";";String s=readStr+newstr;bf.print(s);bf.close();System.out.println("输出到⽂件成功!"+s);}else{System.out.println("⽤户已存在!"+SID);}}//修改⽂件publicstaticvoid UpdateTxt(File f,String SID) throws IOException{ String read;String readStr ="";if(!f.exists()){System.out.println("⽂件不存在!");}else{BufferedReader br =new BufferedReader(new FileReader(f)); while ((read = br.readLine()) !=null) {readStr = readStr + read;}br.close();String[] str1=readStr.split(";");for(int i=0;i<str1.length;i++){String[] str_sid=str1[i].split(",");//System.out.println(str1[i]);if(str_sid[1].equals(SID)){PrintWriter bf=new PrintWriter(new FileWriter(f));String s=readStr.replace(str1[i]+";", "");bf.print(s);bf.close();System.out.println("修改⽂件成功!");break;}}}}}。
⽂件-读、写、追加已经⽂件操作读⽂件:rf=open('test.txt',mode='r')for line in f:print(line)f.close()print本⾝会换⾏,⽂本⾃带⼀个\n,所以有换⾏⼆进制读取:rb写⽂件:w,w会创建新⽂件,有同名则删除内容再写⼊f=open('test1.txt',mode='w',encoding="gbk")#unicode会⾃动转码位gbkf.write("unicode编码写⼊gbk⽂件")f.close()⼆进制写⽂件:wb,wb也会创建⽂件,有同名则删除内容再写⼊图⽚,⾳乐,视频等写⼊需⽤wb模式,⼆进制模式⼆进制模式写字符串到问⽂件,会报错。
提⽰需要⼆进制数据,⾮字符串f=open('test2.txt',mode='wb')#unicode会⾃动转码位gbkf.write("unicode编码写⼊gbk⽂件")f.close()解决以上问题,我们需要⽤encode⽅法,encode⽅法不传参python3默认⽤utf-8进⾏编码f=open('test2.txt',mode='wb')#unicode会⾃动转码位gbkf.write("⼆进制模式写字符串到⽂件,需要先进⾏编码".encode('gbk'))f.close()⽂件追加:a 或ab,源⽂件⽤⼆进制模式追加必须⽤ab模式,否则乱码f=open('test3.txt',mode='a',encoding='gbk')#unicode会⾃动转码位gbkf.write("这是追加部分内容")f.close()混合模式:r+,读的模式打开⽂件,⽀持写⼊,即读写模式w+,写的模式打开⽂件,⽀持读取,即写读模式,w+也会将原有⽂件清楚⽂件操作:fileno()返回⽂件句柄再内核中的索引值,IO多路复⽤会⽤到flush()把⽂件从内存buffer⾥强制刷新到硬盘,close()时会⾃动保存到硬盘写⼊⽂件,但是内容打开是空⽩flush()后会存⼊硬盘readable()判断是否可读以w模式打开,判断是否可读readline()读取⼀⾏,即遇到\r或\n结束seek()把操作⽂件的光标移动到指定位置seek是按字节移动光标,⾄于移动多少个字符,与⽂件编码有关,gbk移动两个字节位⼀个字符,utf8移动三个字节算⼀个字符,read是按字符读取seekable()判断⽂件是否可进⾏seek操作,如设备是不可seek的tell()返回当前⽂件操作光标truncate()从指定位置截取⽂件到末尾,不指定位置则从当前位置截取writable()判断⽂件是否可写修改⽂件先f.seek(),再write()会替换⽂件,⽽且可能会存在乱码。
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();//将写文件指针移到文件尾。