In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use the mid-stream in Java. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
First, the use of the File class
An object of the 1.File class that represents a file or a file directory (commonly known as a folder)
2.File declared under the java.io package.
The 3.File class deals with the creation, deletion, renaming, modification time, file size, and other methods of a file or file directory.
And involves the operation of writing or reading the contents of the file. Entering the palace requires reading or writing the contents of the file, which must be done using an IO stream.
4. Objects of subsequent File classes are often passed as parameters to the stream's constructor, indicating the "end point" of reading or writing.
a. Common constructor
b. Path separator
/ * 1. How to create an instance of File class File (String filePath) File (String parentPath,String,childPath) File (File parentFile,String childPath) 2. Relative path: a well-known path compared to a certain path. Absolute path: the path to the unseen or file directory including the drive letter 3. Path separator windows:\\ unix:/ * / public void test1 () {/ / Constructor 1 File file1 = new File ("hello.txt"); / / relative to module File file2 = new File ("E:\\ zxdym\\ IDEA\\ code\\ JavaSenior\\ 202108\\ he.txt"); System.out.println (file1); System.out.println (file2) / / Constructor 2 File file3 = new File ("E:\ zxdym\\ IDEA\\ code", "JavaSenior"); System.out.println (file3); / / Constructor 3 File file4 = new File (file3, "hi.txt"); System.out.println (file4);} C. Common methods
Public void test2 () {File file1 = new File ("hello.txt"); File file2 = new File ("d:\\ io\\ hi.txt"); System.out.println (file1.getAbsolutePath ()); System.out.println (file1.getPath ()); System.out.println (file1.getName ()); System.out.println (file1.getParent ()) System.out.println (file1.length ()); System.out.println (new Date (file1.lastModified (); System.out.println (); System.out.println (file2.getAbsolutePath ()); System.out.println (file2.getPath ()); System.out.println (file2.getName ()); System.out.println (file2.getParent ()) System.out.println (file2.length ()); System.out.println (file2.lastModified ());} public void test3 () {File file = new File ("E:\ zxdym\ IDEA\ code\ JavaSenior"); String [] list = file.list (); for (String s: list) {System.out.println (s) } System.out.println (); File [] files = file.listFiles (); for (File f: files) {System.out.println (f) }} / * public boolean removeTo (File dest): rename the file to the specified file path such as file1.renameTo (file2) as an example: to ensure that true is returned, file1 needs to exist on the hard disk, and file2 cannot exist on the hard disk. * / @ Test public void test4 () {File file1 = new File ("hello.txt"); File file2 = new File ("D:\\ io\\ hi.txt"); boolean renameTo = file1.renameTo (file2); System.out.println (renameTo);} @ Test public void test5 () {File file1 = new File ("hello.txt"); System.out.println (file1.isDirectory ()) System.out.println (file1.isFile ()); System.out.println (file1.exists ()); System.out.println (file1.canRead ()); System.out.println (file1.canWrite ()); System.out.println (file1.isHidden ());} @ Test public void test6 () throws IOException {File file1 = new File ("hi.txt") If (! file1.exists ()) {file1.createNewFile (); System.out.println ("created successfully");} else {/ / file exists file1.delete (); System.out.println ("deleted successfully") } @ Test public void test7 () {/ / the creation of the file directory File file1 = new File ("e:\ io\\ io1\\ io3"); boolean mkdir = file1.mkdir (); if (mkdir) {System.out.println ("created successfully 1");} File file2 = new File ("e:\ io\\ io1\\ io3") Boolean mkdir1 = file1.mkdirs (); if (mkdir1) {System.out.println ("created successfully 2");}}
d. Pay attention
Second, the classification and system of flow
In development, using buffered flows is more efficient than node flows (important and commonly used in the blue box)
The standardization process of input and output 1. Input process
a. Create an object of the File class that indicates the source of the data read. (this file is required to exist)
b. Create the corresponding input stream and input the object of the File class as a parameter to the constructor of the stream
c. The specific reading process:
Create the corresponding byte [] or char []
d. Turn off streaming resources
Note: exceptions in the program need to be handled by try-catch-finally.
two。 Output process
a. Create an object of the File class that indicates the source of the written data. (this file is required to exist)
b. Create the corresponding output stream and pass the object of the File class as a parameter to the constructor of the stream
c. The specific writing process:
Write (char [] / byte [] buffer,0,len)
d. Turn off streaming resources
Note: exceptions in the program need to be handled by try-catch-finally.
Public class FileReaderWriterTest {public static void main (String [] args) {File file = new File ("hello.txt"); / / compared to the previous project System.out.println (file.getAbsolutePath ()); File file1 = new File ("2021 / 08\\ hello.txt"); System.out.println (file1.getAbsolutePath ()) } / * read the contents of the hello.txt file under day09 into the program, and output to the console description point: the understanding of 1.read (), returns a character read, and returns-1.2 if the end of the file is reached. Exception handling: in order to ensure that flow resources must be able to perform a close operation. You need to use try-catch-finally to handle 3. The file you read must exist, otherwise it will be reported to FileNotFoundException. * / @ Test public void testFileReader () {FileReader fr = null; try {/ / 1. Instantiate the object of the File class, indicating the file File file = new File ("hello.txt") to be operated on; / / compared to the current Module / / 2. Provide a specific stream fr = new FileReader (file); / / 3. Data read / / read (): returns a character read. If the end of the file is reached, return-1 / / mode 1: / / int data = fr.read (); / / while (data! =-1) {/ / System.out.print ((char) data); / / data = fr.read () / / Mode 2: syntax modification int data; while ((data = fr.read ())! =-1) {System.out.print ((char) data);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 4. Try {if (fr! = null) fr.close ();} catch (IOException e) {e.printStackTrace ();} finally {} @ Test public void testFileReader1 () {FileReader fr = null Instantiation of try {/ / 1.File class File file = new File ("hello.txt"); / / instantiation of 2.FileReader stream fr = new FileReader (file); / / 3. Read operation / / read (char [] cbuf): returns the number of characters read into the cbuf array each time. If the end of the file is reached, return-1 char [] cbuf = new char [5]; int len While ((len = fr.read (cbuf))! =-1) {/ / method 1: / / incorrect writing / / knowledge point difficulty: covering / / for of array elements (int I = 0 position I)
< cbuf.length;i++){// System.out.print(cbuf[i]);// } //正确的写法// for(int i = 0;i < len;i++){// System.out.print(cbuf[i]);// } //方式二: //错误的写法,对应着方式一的错误的写法// String str = new String(cbuf);// System.out.println(str); //正确的写法 String str = new String(cbuf, 0, len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if(fr != null){ //4.资源的关闭 try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* 从内存中写出数据到硬盘的文件里 说明: 1.输出操作,对应的File可以不存在的,并不会报异常 2. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件 File对应的硬盘中的文件如果存在: 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容 */ @Test public void testFileWriter() { FileWriter fw = null; try { //1.提供File类的对象,指明写出到的文件 File file = new File("hello1.txt"); //2.提供FileWriter的对象,用于数据的写出 fw = new FileWriter(file,false); //3.写出的操作 fw.write("I have a dream!\n"); fw.write("you need to have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { //4.流资源的关闭 if(fw != null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testFileReaderFileWriter(){ FileReader fr = null; FileWriter fw = null; try { //1.创建File类的对象,指明读入和写出的文件 File srcFile = new File("hello.txt"); File destFile = new File("hello2.txt"); //不能使用字符流来处理图片等字节数据// File srcFile = new File("爱情与友情.jpg"); File destFile = new File("爱情与友情1.jpg"); //2.创建数据入流和输出流的对象 fr = new FileReader(srcFile); fw = new FileWriter(destFile); //3.数据的读入和写出操作 char[] cbuf = new char[5]; int len;//记录每次读入到cbuf数组中的字符的个数 while((len = fr.read(cbuf)) != -1){ //每次写出len个字符 fw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally {// //4.关闭流资源// //方式一:// try {// fw.close();// } catch (IOException e) {// e.printStackTrace();// }finally {// try {// fr.close();// } catch (IOException e) {// e.printStackTrace();// }// } //方式二: try { fw.close(); } catch (IOException e) { e.printStackTrace(); } try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } }}三、流的详细介绍1.字节流和字符流测试FileInputStream和FileOutputStream的使用 public class FileInputOutputStreamTest { //使用字节流FileInputOutputStream处理文本文件,可能出现乱码 @Test public void testFileInputStream(){ FileInputStream fis = null; try { //1.造文件 File file = new File("hello.txt"); //2.造流 fis = new FileInputStream(file); //3.读数据 byte[] buffer = new byte[5]; int len;//记录每次读取的字节的个数 while((len = fis.read(buffer)) != -1){ String str = new String(buffer, 0, len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭资源 try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } /* 实现对图片的复制操作 */ @Test public void testFileInputOutputStream(){ FileInputStream fis = null; FileOutputStream fos = null; try { File srcFile = new File("爱情与友情.jpg"); File destFile = new File("爱情与友情2.jpg"); fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //复制的过程 byte[] buffer = new byte[5]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } //指定路径下文件的复制 public void copyFile(String srcPath,String destPath){ FileInputStream fis = null; FileOutputStream fos = null; try { File srcFile = new File(srcPath); File destFile = new File(destPath); fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //复制的过程 byte[] buffer = new byte[5]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testCopyFile(){ long start = System.currentTimeMillis(); String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi"; String destPath = "C:\\Users\\Administrator\\Desktop\\02-视频.avi"; copyFile(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("复制操作花费的时间为:" + (end - start)); }} 结论: 1.对于文本文件(.txt,.java,.c,.cpp),使用字符流处理 2.对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字节流处理 2.节点流和处理流(重点) 处理流之一:缓冲流的作用 1.缓冲流: BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter 2.作用:提高流的读取,写入的速度 提高读写速度的原因:内部提供了一个缓冲区,默认情况是8kb 3.处理流:就是"套接"在已有流的基础上 public class BufferedTest { @Test public void BufferedStreamTest(){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.造文件 File srcFile = new File("爱情与友情.jpg"); File destFile = new File("爱情与友情3.jpg"); //2.造流 //2.1造节点流 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //2.2造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.复制的细节:读取、写入 byte[] buffer = new byte[10]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len);// bos.flush();//刷新缓冲区 } } catch (IOException e) { e.printStackTrace(); } finally { //4.资源关闭 //要求:先关闭外层的流,再关闭内层的流 if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //说明:关闭外层流的同时,内层流也会自动的进行关闭,关于内层流的关闭,可以省略// fos.close();// fis.close(); } } @Test public void testCopyFileWithBuffered(){ long start = System.currentTimeMillis(); String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi"; String destPath = "C:\\Users\\Administrator\\Desktop\\03-视频.avi"; copyFileWithBuffered(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("复制操作花费的时间为:" + (end - start)); } //实现文件复制的方法 public void copyFileWithBuffered(String srcPath,String destPath) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.造文件 File srcFile = new File(srcPath); File destFile = new File(destPath); //2.造流 //2.1造节点流 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //2.2造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.复制的细节:读取、写入 byte[] buffer = new byte[10]; int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.资源关闭 //要求:先关闭外层的流,再关闭内层的流 if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //说明:关闭外层流的同时,内层流也会自动的进行关闭,关于内层流的关闭,可以省略// fos.close();// fis.close(); } } /* 使用BufferedReader和BufferedWriter实现文本文件的复制 */ @Test public void testBufferedReaderBufferedWriter(){ BufferedReader br = null; BufferedWriter bw = null; try { //创建文件和相应的流 br = new BufferedReader(new FileReader(new File("dpcp.txt"))); bw = new BufferedWriter(new FileWriter(new File("dpcp1.txt"))); //读写操作 //方式一:使用char[]数组// char[] cbuf = new char[1024];// int len;// while((len = br.read(cbuf)) != -1){// bw.write(cbuf,0,len);// } //方式二:使用String String data; while((data = br.readLine()) != null){ //方法一: bw.write(data + "\n");//data中不包含换行符 //方法二: bw.write(data);//data中不包含换行符 bw.newLine();//提供换行的操作 } } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 if(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }} 处理流之二:转换流的使用(重点) 1.转换流:属于字符流 InputStreamReader:将一个字节的输入流转换为字符的输入流 OutputStreamWriter:将一个字符的输出流转换为字节的输出流two。 Function: provides conversion between byte stream and character stream
3. Decoding: byte, byte array-- > character array, string
Encoding: character array, string-- > bytes, byte array
Description: coding determines the way it is decoded
4. Character set
Description: the way the file is encoded (for example, GBK) determines the character set used for parsing (only GBK)
Public class InputStreamReaderTest {/ * if you handle exceptions at this time, you should still use try-catch-finally * / @ Test public void test1 () throws IOException {FileInputStream fis = new FileInputStream ("dbcp.txt"); / / InputStreamReader isr = new InputStreamReader (fis) / / use the system default character set / / Parameter 2 to indicate the character set, depending on which character set is used when saving the file dbcp.txt InputStreamReader isr = new InputStreamReader (fis, "UTF-8"); char [] cbuf = new char [20]; int len While ((len = isr.read (cbuf))! =-1) {String str = new String (cbuf,0,len); System.out.print (str);} isr.close () } / * if you handle exceptions at this time, you should still use try-catch-finally to combine InputStreamReader and OutputStreamWriter * / @ Test public void test2 () throws Exception {/ / 1. File file1 = new File ("dbcp.txt"); File file2 = new File ("dbcp_gbk.txt"); FileInputStream fis = new FileInputStream (file1); FileOutputStream fos = new FileOutputStream (file2); InputStreamReader isr = new InputStreamReader (fis, "UTF-8"); OutputStreamWriter osw = new OutputStreamWriter (fos, "gbk"); / / 2. Char [] cbuf = new char [20]; int len; while ((len = isr.read (cbuf))! =-1) {osw.write (cbuf,0,len);} / / 3. Close the resource isr.close (); osw.close ();}}
3. Other streams 1. Standard input and output streams
1.1System.in: standard input stream, input from keyboard by default
System.out: standard input stream, output from the console by default
The setIn () / setOut () mode of the 1.2System class reassigns the input and output streams.
Modify the default input and output behavior:
The setIn (InputStream is) / setOut (PrintStream ps) mode of the System class re-specifies the input and output streams.
1.3 activity:
Entering a string from the keyboard requires that the read moral entire line of string be converted to uppercase output. Then continue with the input operation.
Exit the program until you type "e" or "exit"
Method 1: use Scanner to implement and call next () to return a string
Method 2: use System.in to implement. System.in-> conversion stream-- > readLine () of BufferedReader
Public static void main (String [] args) {BufferedReader br = null; try {InputStreamReader isr = new InputStreamReader (System.in); br = new BufferedReader (isr); while (true) {System.out.println ("Please enter string:"); String data = br.readLine () / / call this method to read a row of data if ("e" .equalsIgnoreCase (data) | | "exit" .equalsIgnoreCase (data)) {/ / avoid null pointer writing, preceded by System.out.println ("Program ends"); break;} String upperCase = data.toUpperCase () System.out.println (upperCase);}} catch (IOException e) {e.printStackTrace ();} finally {if (br! = null) {try {br.close ();} catch (IOException e) {e.printStackTrace () }}
Object flow (emphasis)
The use of object streams
1.ObjectInputStream and ObjectOutputStream
two。 Purpose: a processing stream used to store and read basic data types or objects.
3. If you want a Java object to be serializable, you need to meet the corresponding requirements. See Person.java
4. Serialization mechanism: (key point! )
The object serialization mechanism allows Java objects in memory to be converted into platform-independent binary streams, thus allowing such binary streams to be persisted on disk or over the network.
The binary stream is transmitted to another network node, and when other programs acquire the binary stream, it can be restored to the original Java object.
Serialization process: save java objects in memory to disk or transfer them out over the network using ObjectOutputStream to achieve @ Test public void testObjectOutputStream () {ObjectOutputStream oos = null; try {oos = new ObjectOutputStream (new FileOutputStream ("object.dat")); oos.writeObject (new String ("I love Beijing Tiananmen"); oos.flush () / / refresh operation oos.writeObject (new Person ("Wang Ming", 23)); oos.flush ();} catch (IOException e) {e.printStackTrace ();} finally {if (oos! = null) {try {oos.close () } catch (IOException e) {e.printStackTrace ();}} deserialization: restore an object in a disk file to a Java object in memory using ObjectInputStream to implement @ Test public void testObjectInputStream () {ObjectInputStream ois = null Try {ois = new ObjectInputStream (new FileInputStream ("object.dat")); Object obj = ois.readObject (); String str = (String) obj; Person p = ois.readObject (); System.out.println (str); System.out.println (p);} catch (IOException e) {e.printStackTrace () } catch (ClassNotFoundException e) {e.printStackTrace ();} finally {if (ois! = null) {ois.close;}} Person class
Person needs to meet the following requirements before serialization
1. You need to implement the interface: Serializable
two。 The current class provides a global constant: serialVersionUID
3. In addition to the current Person class that needs to implement the Serializable interface, you must ensure that all of its internal properties must also be serializable (by default, the base data type, String: itself is serializable)
Add: ObjectOutputStream and ObjectInputStream cannot serialize member variables modified by static and transient
Eg: output result: Person {name='null',age=0,id=0,acct=null}
Public class Person implements Serializable {public static final long serialVersionUID = 397497937034L; private String name; private int age; @ Override public String toString () {return "Person {" + "name='" + name +'\'+ ", age=" + age +'}';} public String getName () {return name } public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age;} public Person (String name, int age) {this.name = name; this.age = age;} public Person () {}} object serialization mechanism
Random access file stream (understanding)
RandomAccessFile 1.RandomAccessFile inherits directly from the java.lang.Object class and implements the DataInput and DataOutput interfaces 2.RandomAccessFile as both an input stream and an output stream. If the written file does not exist when RandomAccessFile is used as the output stream, it is automatically created during execution. If the written file exists, the contents of the original file are overwritten (by default, overwritten from scratch) 4. You can use related operations to achieve the effect of RandomAccessFile "inserting" data public abstract class RandomAccessFileTest {@ Test public void test1 () {RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try {raf1 = new RandomAccessFile (new File ("love and friendship .jpg"), "r"); raf2 = new RandomAccessFile (new File ("1.jpg"), "rw") Byte [] buffer = new byte [1024]; int len; while ((len = raf1.read (buffer))! =-1) {raf2.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace () } finally {if (raf1! = null) {try {raf1.close ();} catch (IOException e) {e.printStackTrace () }} if (raf2! = null) {try {raf2.close ();} catch (IOException e) {e.printStackTrace () } @ Test public void test2 () throws IOException {RandomAccessFile raf1 = new RandomAccessFile ("hello.txt", "rw"); raf1.seek (3); / / adjust the pointer to the position marked at corner 3 raf1.write ("xyz" .getBytes ()); / / raf1.close () } use RandomAccessFile to achieve data insertion @ Test public void test3 () throws IOException {RandomAccessFile raf1 = new RandomAccessFile ("hello.txt", "rw"); raf1.seek (3); / set the pointer to the position marked with corner 3 / / save all data after pointer 3 to StringBuilder StringBuilder builder = new StringBuilder ((int) new File ("hello.txt" .length () Byte [] buffer = new byte [20]; int len; while ((len = raf1.read (buffer))! =-1) {builder.append (new String (buffer,0,len));} / / recall the pointer and write "xyz" raf1.seek (3); raf1.write ("xyz" .getBytes ()) / / write the data in StringBuilder to the file raf1.write (builder.toString () .getBytes ()); raf1.close ();}} NIO in Java
This is the end of the article on "how to use the stream in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.