使用BigDecimal
,而不是double
adatapost的答案关于使用是正确的,String::split
但关于使用double
来表示您的经纬度值是错误的。/和float
/类型使用浮点技术,以牺牲准确性换取执行速度。Float
double
Double
而是使用BigDecimal
正确表示您的经纬度值。
使用Apache Commons CSV库
此外,最好让诸如Apache Commons CSV之类的库来执行读取和写入CSV或制表符分隔文件的繁琐工作。
示例应用
这是一个使用Commons CSV库的完整示例应用程序。此应用程序写入然后读取数据文件。它String::split
用于写作。该应用程序使用BigDecimal
对象来表示您的经纬度值。
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class LatLong
{
//----------| Write |-----------------------------
public void write ( final Path path )
{
List < String > inputs =
List.of(
"28.515046280572285,77.38258838653564" ,
"28.51430151808072,77.38336086273193" ,
"28.513566177802456,77.38413333892822" ,
"28.512830832397192,77.38490581512451" ,
"28.51208605426073,77.3856782913208" ,
"28.511341270865113,77.38645076751709" );
// Use try-with-resources syntax to auto-close the `CSVPrinter`.
try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
{
for ( String input : inputs )
{
String[] fields = input.split( "," );
printer.printRecord( fields[ 0 ] , fields[ 1 ] );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Read |-----------------------------
public void read ( Path path )
{
// TODO: Add a check for valid file existing.
try
{
// Read CSV file.
BufferedReader reader = Files.newBufferedReader( path );
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
for ( CSVRecord record : records )
{
BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
System.out.println( "lat: " + latitude + " | long: " + longitude );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Main |-----------------------------
public static void main ( String[] args )
{
LatLong app = new LatLong();
// Write
Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.write( pathOutput );
System.out.println( "Writing file: " + pathOutput );
// Read
Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.read( pathInput );
System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
}
}