In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what is the method of reading data from a file by JAVA". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1.Scanner
The first way is Scanner. API, which is provided from JDK1.5, is characterized by being able to read file data by line and separator. It can read not only String type, but also Int type, Long type and other basic data types.
[@ Test] (https://my.oschina.net/azibug)void testReadFile1 () throws IOException {/ / File content: Hello World | Hello Zimug String fileName = "D:\\ data\\ test\\ newFile4.txt"; try (Scanner sc = new Scanner (new FileReader (fileName) {while (sc.hasNextLine ()) {/ / read the string String line = sc.nextLine () by line; System.out.println (line) }} try (Scanner sc = new Scanner (new FileReader (fileName)) {sc.useDelimiter ("\\ |"); / / delimiter while (sc.hasNext ()) {/ / read the string String str = sc.next () by delimiter; System.out.println (str);}} / / sc.hasNextInt (), hasNextFloat (), underlying data type, and so on. / / File content: 1 | 2 fileName = "D:\\ data\\ test\\ newFile5.txt"; try (Scanner sc = new Scanner (new FileReader (fileName) {sc.useDelimiter ("\\ |"); / / Delimiter while (sc.hasNextInt ()) {/ / read Int int intValue = sc.nextInt (); System.out.println (intValue);}
The output of the above method is as follows:
Hello World | Hello ZimugHello WorldHello Zimug122.Files.lines (Java 8)
If you need to deal with the contents of the data file by line, this is a way that I recommend you to use, the code is simple, use the Stream stream of java 8 to organically integrate file reading and file processing.
[@ Test] (https://my.oschina.net/azibug)void testReadFile2 () throws IOException {String fileName = "D:\ data\\ test\\ newFile.txt"; / / read the contents of the file into the Stream stream and read Stream lines = Files.lines (Paths.get (fileName)) by line; / / data processing lines.forEach (ele-> {System.out.println (ele);});}
ForEach cannot guarantee the order of the row data in the Stream stream, but it is fast. If you want to process the line data in the file sequentially, you can use forEachOrdered, but the processing efficiency will be reduced.
/ / process lines.forEachOrdered (System.out::println) in the order of file lines
Or make use of the multi-sum ability of CPU to carry out parallel data processing parallel (), which is suitable for larger files.
/ / process lines.parallel () .forEachOrdered (System.out::println) in the order of file lines
You can also convert Stream to List, but note that this means that you have to load all the data into memory at once, and pay attention to java.lang.OutOfMemoryError
/ / convert to List, pay attention to java.lang.OutOfMemoryError: Java heap spaceList collect = lines.collect (Collectors.toList ()); 3.Files.readAllLines
This method is still provided for us by java8. If we don't need Stream and we want to read the file directly by line to get a List, we will use the following method. The same problem: this means that you have to load all the data into memory at once, and pay attention to java.lang.OutOfMemoryError
[@ Test] (https://my.oschina.net/azibug)void testReadFile3 () throws IOException {String fileName = "D:\ data\\ test\\ newFile3.txt"; / / convert to List, note that java.lang.OutOfMemoryError: Java heap space List lines = Files.readAllLines (Paths.get (fileName), StandardCharsets.UTF_8); lines.forEach (System.out::println);} 4.Files.readString (JDK 11)
Starting with java11, it gives us a way to read a file at once. Files cannot exceed 2 gigabytes, and pay attention to your server and JVM memory. This method is suitable for reading small text files quickly.
[@ Test] (https://my.oschina.net/azibug)void testReadFile4 () throws IOException {String fileName = "D:\\ data\\ test\\ newFile3.txt"; / / the method provided at the beginning of java 11: read files cannot exceed 2GB, which is closely related to your memory / / String s = Files.readString (Paths.get (fileName));} 5.Files.readAllBytes ()
What if you don't have JDK11 (readAllBytes () starts with JDK7) and still want to quickly read the contents of a file to String at once? The data is read into a binary array and then converted into String content. This method is suitable for reading small text files quickly if there is no JDK11.
[@ Test] (https://my.oschina.net/azibug)void testReadFile5 () throws IOException {String fileName = "D:\ data\\ test\\ newFile3.txt"; / / if JDK11 uses the above method, it is easy to byte [] bytes = Files.readAllBytes (Paths.get (fileName)); String content = new String (bytes, StandardCharsets.UTF_8); System.out.println (content);} 6. The way of classic pipeline flow
The last one is the classic way of pipeline flow.
@ Testvoid testReadFile6 () throws IOException {String fileName = "D:\ data\\ test\\ newFile3.txt"; / / buffered stream read, default buffer 8k try (BufferedReader br = new BufferedReader (new FileReader (fileName) {String line; while ((line = br.readLine ())! = null) {System.out.println (line) }} / / java 8 can also be written in try (BufferedReader br = Files.newBufferedReader (Paths.get (fileName) {String line; while ((line = br.readLine ())! = null) {System.out.println (line);}
This method can be used in combination through the nesting of pipeline flows, and it is more flexible. For example, if we want to read java Object from a file, we can use the following code, provided that the data in the file is written by ObjectOutputStream before it can be read with ObjectInputStream.
That's all for try (FileInputStream fis = new FileInputStream (fileName); ObjectInputStream ois = new ObjectInputStream (fis)) {ois.readObject ();} "what is the way JAVA reads data from a file". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.