File file = new File ("http: // 127.0.0.1: 8080/aa.txt") cannot be used directly for reading, because the transmission protocol on the network is HTTP, which is different from that on the local machine, use URL to read
The code is as follows: |
Copy code |
String output = ""; File file = new File ("E: // bb.txt "); URL MyURL = new URL ("http: // 127.0.0.1: 8080/aa.txt "); URLConnection uc = MyURL. openConnection (); Uc. connect (); InputStreamReader _ Input = new InputStreamReader (uc. getInputStream (), "UTF-8 "); BufferedReader br = new BufferedReader (_ Input ); String s = ""; While (s = br. readLine ())! = Null ){ Output + = s; } FileWriter fw = new FileWriter (file ); Fw. write (output ); Fw. flush (); Fw. close (); |
If you want to read and write large files, the above method may not work.
I started to use the following reading method:
The code is as follows: |
Copy code |
BufferedReader br = new BufferedReader (new FileReader (this. datafile )); String line; Int numofline = 0; While (br. ready ()){...} |
There is no problem in reading and writing large files using bufferedreader. Finally, after careful study, the problem occurs in the judgment condition of the while loop. Ready () is used to judge that the input stream is aborted, not necessarily the end of the file. To judge the end of a file, use the following statement:
The code is as follows: |
Copy code |
(Line = br. readLine ())! = Null |
In this way, the original file can be read. The original statement read only a small part of the source file.
Opencsv
OpenCSV is a simple java Class Library used to parse CSV files. It encapsulates the output and reading of CSV files and can automatically process special characters in CSV format, most importantly, OpenCSV can be used for commercialization (commercial-friendly ).
Specific usage:
Read CSV files
1. Read using Iterator
The code is as follows: |
Copy code |
CSVReader reader = new CSVReader (new FileReader ("yourfile.csv ")); String [] nextLine; While (nextLine = reader. readNext ())! = Null ){ // NextLine [] is an array of values from the line System. out. println (nextLine [0] + nextLine [1] + "etc ..."); } |
2. Use List
The code is as follows: |
Copy code |
CSVReader reader = new CSVReader (new FileReader ("yourfile.csv ")); List myEntries = reader. readAll (); |
Write CSV files
1. Similar to FileReader
CSV
The code is as follows: |
Copy code |
Writer writer = new CSVWriter (new FileWriter ("yourfile.csv"), 'T '); // Feed in your array (or convert your data to an array) String [] entries = "first # second # third". split ("#"); Writer. writeNext (entries );
|
Writer. close ();