Java 8 only needs one line of code to read files-Beijing shangxue and Java 8

Source: Internet
Author: User

Java 8 only needs one line of code to read files-Beijing shangxue and Java 8

Java 8 only needs one line of code to read a file


This method ensures that the file attribute is disabled when all the bytes of the file are read. Otherwise, an IO exception or other unchecked exceptions will occur. This means that you do not need to close the file after reading the last part of the file. Note that this method is not suitable for reading large files because there may be insufficient memory space. Developers should also specify the character encoding of the file to avoid any exceptions or parsing errors. JDK 7 introduces a new file operation class java. nio. file. file, which contains many useful methods to operate files, such as checking whether the File is a hidden File or whether the File is a read-only File. Developers can also use the Files. readAllBytes (Path) method to read the entire file into the memory. This method returns a byte array and passes the result to the String constructor to create String output.

 

If you want to read the file as a string, you can also use the readAllLines (Path path, Charset cs) method. This method is similar to the previous method, and you do not need to close the file after reading the file. However, it returns a string array instead of a byte array. Furthermore, Java 8 overrides this method and directly uses UTF-8 encoding for String Conversion without specifying character sets.
If you want to read Files in one row as strings, you can use Files. the lines () method that returns a string stream from the Read File and converts bytes into characters using UTF-8 encoding. Using the forEach () method, you can use only one line of Java code to output all the content of the file to the console, as shown in the third code snippet below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Import java. io. IOException;

Import java. nio. charset. StandardCharsets;

Import java. nio. file. Files;

Import java. nio. file. Paths;

Import java. util. List;

Public class FileReadingTest {

Public static void main (String [] args) throws IOException {

// Java 7 example

// Files. readAllBytes by default to the UTF-8 encoding to read Files, so if the file encoding is not a UTF-8, then the Chinese content will appear messy characters

System. out. println (new String (Files. readAllBytes (Paths. get ("D: \ jd.txt "))));

// Java 8 example

List <string> <span id = "3_nwp" style = "width: auto; height: auto; float: none;">

<A id = "3_nwl" href = "http://cpro.baidu.com/cpro/ui/uijs.php? Adclass = 0 & app_id = 0 & c = news & cf = 1001 & ch = 0 & di = 128 & fv = 20 & is _

App = 0 & jk = eca29f2ba2403d7f & k = line & k0 = line & kdi0 = 0 & luki = 3 & mcpm = 0 & n = 10 & p = baidu & q = 06011078 _

Cpr & rb = 0 & rs = 1 & seller_id = 1 & sid = 7f3d40a22b9fa2ec & ssp2 = 1 & stid = 9 & t = tpclicked3

_ Hc & td = 1922429 & tu = u1922429 & u = http % 3A % 2F % 2 Fwww % 2Eadmin10000% 2 Ecom % 2 Fdocument % 2F6039% 2 Ehtml & urlid = 0"

Target = "_ blank" mpid = "3" style = "text-decoration: none;">

<Span style = "color: # 0000ff; font-size: 14px; width: auto; height: auto; float: none;">

Line </span> </a> </span> s = Files. readAllLines (Paths. get ("D: \ jd.txt"), StandardCharsets. UTF_8 );

StringBuilder sb = new StringBuilder ();

For (String line: lines ){

Sb. append (line );

}

String <span id = "4_nwp" style = "width: auto; height: auto; float: none;"> <a id = "4_nwl" href = "http://cpro.baidu.com/cpro/ui/uijs.php? Adclass = 0 & app_id = 0 & c = news & cf = 1001 & ch = 0 & di = 128 & fv = 20 & is

_ App = 0 & jk = eca29f2ba2403d7f & k = from & k0 = from & kdi0 = 0 & luki = 1 & mcpm = 0 & n = 10 & p = baidu & q = 06011078 _

Cpr & rb = 0 & rs = 1 & seller_id = 1 & sid = 7f3d40a22b9fa2ec & ssp2 = 1 & stid = 9 & t = tpclicked3

_ Hc & td = 1922429 & tu = u1922429 & u = http % 3A % 2F % 2 Fwww % 2Eadmin10000% 2 Ecom % 2 Fdocument % 2F6039% 2 Ehtml & urlid = 0"

Target = "_ blank" mpid = "4" style = "text-decoration: none;"> <span style = "color: # 0000ff; font-size: 14px; width: auto; height: auto; float: none; "> from </span> </a> </span> File = sb. toString ();

System. out. println (fromFile );

}

} </String>

If JDK 7 is not used, but JDK 8, a line of code can be used to read the file.

1

2

3

4

5

6

7

8

9

10

11

Import static <span id = "2_nwp" style = "width: auto; height: auto; float: none;"> <a id = "2_nwl" href = "http://cpro.baidu.com/cpro/ui/uijs.php? Adclass = 0 & app _

Id = 0 & c = news & cf = 1001 & ch = 0 & di = 128 & fv = 20 & is_app = 0 & jk = eca29f2ba2403d7f & k = java & k0 = java & kdi0 = 0 & luki = 5 & mcpm = 0 & n = 10 & p = baidu & q = 06011078 _

Cpr & rb = 0 & rs = 1 & seller_id = 1 & sid = 7f3d40a22b9fa2ec & ssp2 = 1 & stid = 9 & t = tpclicked3

_ Hc & td = 1922429 & tu = u1922429 & u = http % 3A % 2F % 2 Fwww % 2Eadmin10000% 2 Ecom % 2 Fdocument % 2F6039% 2 Ehtml & urlid = 0 "target = "_ blank" mpid = "2"

Style = "text-decoration: none;"> <span style = "color: # 0000ff; font-size: 14px; width: auto; height: auto; float: none; "> java </span> </a> </span>. lang. system. out;

Import static java. nio. file. Files. readAllBytes;

Import static java. nio. file. Paths. get;

Import java. io. IOException;

Public class filepath string {

Public static void main (String [] args) throws IOException {

// A line of code to get read files, the default is UTF-8 Encoding

Out. println (new String (readAllBytes (get ("d:/jd.txt "))));

}

}

If JDK 8 is used, you can use stream APIs to read and write files. This makes the code more concise and efficient. In the following example, the lines () method returns the string stream, which uses UTF-8 encoding. As follows:

1

2

3

4

5

6

7

8

9

10

11

12

Import java. io. IOException;

Import java. nio. charset. StandardCharsets;

Import java. nio. file. Files;

Import java. nio. file. Paths;

Public class Java8FileReader {

Public static void main (String [] args) throws IOException {

// Java 8 reads files in streaming mode, making it more efficient

Files. <span id = "Your NWP" style = "width: auto; height: auto; float: none;"> <a id = "Your nwl" href = "http://cpro.baidu.com/cpro/ui/uijs.php? Adclass = 0 & app_id = 0 & c = news & cf = 1001 & ch = 0 & di = 128 & fv = 20 & is_app = 0 & jk = eca29f2ba2403d7f & k = line & k0 = line & kdi0 = 0 & luki = 3 & mcpm = 0 & n = 10 & p = baidu & q= 06011078 _

Cpr & rb = 0 & rs = 1 & seller_id = 1 & sid = 7f3d40a22b9fa2ec & ssp2 = 1 & stid = 9 & t = tpclicked3 _

Hc & td = 1922429 & tu = u1922429 & u = http % 3A % 2F % 2 Fwww % 2Eadmin10000% 2 Ecom % 2 Fdocument % 2F6039% 2 Ehtml & urlid = 0 "target = "_ blank" mpid = "1" style = "text-decoration: none; "> <span style =" color: # 0000ff; font-size: 14px; width: auto; height: auto; float: none; "> line </span> </a> </span> s (Paths. get ("D: \ jd.txt"), StandardCharsets. UTF_8 ). forEach (System. out: println );

}

}

Note the following points in the preceding example:

1) the file may be large and may exceed the memory space. Evaluate the file before use.

2) Output logs to record why the file cannot be read or any errors encountered when reading the file.

3) when converting bytes into characters, character encoding should be specified.

4) the file to be processed does not exist.

Note that if the Read File is ANSI encoded, the preceding example reports a java. nio. charset. MalformedInputException: Input length = 1 error when reading the file content.

 

 

[For the latest document updates, please join Shang xuexiang www.sxt.cn] [professional IT training institutions, real zero down payment admission www.bjsxt.com]

Beijing shangxuetao-cctv advertising partners, professional IT training institutions, best-of-mouth java training, iOS training, android training, hadoop big data training, web Front-end training institutions, 0 Yuan admission, payment after employment, with an average employment salary of more than 9500.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.