如何从Java文本文件中读取逗号分隔的值?
我得到了这个文本文件,其中包含地图上不同点的纬度和经度值 我怎样才能把我的绳子分成纬度和经度?使用其他分隔符(如空格或制表符等)进行此类操作的一般方法是什么。? 示例文件:如何从Java文本文件中读取逗号分隔的值?,java,string,io,Java,String,Io,我得到了这个文本文件,其中包含地图上不同点的纬度和经度值 我怎样才能把我的绳子分成纬度和经度?使用其他分隔符(如空格或制表符等)进行此类操作的一般方法是什么。? 示例文件: 28.515046280572285,77.38258838653564 28.51430151808072,77.38336086273193 28.513566177802456,77.38413333892822 28.512830832397192,77.38490581512451 28.5120860542607
28.515046280572285,77.38258838653564
28.51430151808072,77.38336086273193
28.513566177802456,77.38413333892822
28.512830832397192,77.38490581512451
28.51208605426073,77.3856782913208
28.511341270865113,77.38645076751709
这是我用来读取文件的代码:
try(BufferedReader in = new BufferedReader(new FileReader("C:\\test.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e) {
System.out.println("File Read Error");
}
您可以使用以下方法:
然后,使用方法将字符串值解析为double
double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);
其他包装器类中也存在类似的解析方法-
Integer
、Boolean
等。使用OpenCSV提高可靠性。斯普利特不应该被用于这类事情。
这是我自己的一个程序的一个片段,非常简单。我检查是否指定了分隔符,如果是,则使用此分隔符;如果不是,则使用OpenCSV中的默认分隔符(逗号)。然后我读取标题和字段
CSVReader reader = null;
try {
if (delimiter > 0) {
reader = new CSVReader(new FileReader(this.csvFile), this.delimiter);
}
else {
reader = new CSVReader(new FileReader(this.csvFile));
}
// these should be the header fields
header = reader.readNext();
while ((fields = reader.readNext()) != null) {
// more code
}
catch (IOException e) {
System.err.println(e.getMessage());
}
要使用逗号(,)拆分字符串,请使用
str.split(,”
,对于制表符,请使用str.split(\\t”)
//lat=3434&lon=yy38&rd=1.0&
以该格式显示o/p
public class ReadText {
public static void main(String[] args) throws Exception {
FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(f));
String strline;
StringBuffer sb = new StringBuffer();
while ((strline = br.readLine()) != null)
{
String[] arraylist=StringUtils.split(strline, ",");
if(arraylist.length == 2){
sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");
} else {
System.out.println("Error: "+strline);
}
}
System.out.println("Data: "+sb.toString());
}
}
您还可以使用java.util.Scanner类
private static void readFileWithScanner() {
File file = new File("path/to/your/file/file.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] lineArray = line.split(",");
// do something with lineArray, such as instantiate an object
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scan.close();
}
}
使用BigDecimal
,而不是double
使用String::split
是正确的,但使用double
表示经纬度值是错误的。float
/float
和double
/double
类型用于提高执行速度
而是使用来正确表示lat long值
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() );
}
}
使用ApacheCommonsCSV库
此外,最好让库(如)执行读写或文件的杂务
示例应用程序
下面是一个使用Commons CSV库的完整示例应用程序。此应用程序先写入数据文件,然后读取数据文件。它使用String::split
进行编写。应用程序使用BigDecimal
对象来表示你的lat-long值
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() );
}
}
package work.basil.example;
导入org.apache.commons.csv.CSVFormat;
导入org.apache.commons.csv.CSVPrinter;
导入org.apache.commons.csv.CSVRecord;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.math.BigDecimal;
导入java.nio.charset.StandardCharset;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.time.Instant;
导入java.util.List;
导入java.util.concurrent.ThreadLocalRandom;
公共类拉特朗
{
//----------|写|-----------------------------
公共无效写入(最终路径)
{
列出输入=
名单(
"28.515046280572285,77.38258838653564" ,
"28.51430151808072,77.38336086273193" ,
"28.513566177802456,77.38413333892822" ,
"28.512830832397192,77.38490581512451" ,
"28.51208605426073,77.3856782913208" ,
"28.511341270865113,77.38645076751709" );
//使用try with resources语法自动关闭“CSVPrinter”。
try(最终CSVPrinter打印机=CSVFormat.RFC4180.withHeader(“纬度”、“经度”)。打印(路径,StandardCharsets.utf8);)
{
for(字符串输入:输入)
{
String[]fields=input.split(“,”);
printer.printRecord(字段[0],字段[1]);
}
}捕获(IOE异常)
{
e、 printStackTrace();
}
}
//----------|阅读|-----------------------------
公共无效读取(路径)
{
//TODO:添加对现有有效文件的检查。
尝试
{
//读取CSV文件。
BufferedReader reader=Files.newBufferedReader(路径);
Iterablerecords=CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
用于(CSVRecord记录:记录)
{
BigDecimal纬度=新的BigDecimal(record.get(“纬度”));
BigDecimal经度=新的BigDecimal(record.get(“经度”));
System.out.println(“纬度:+纬度+”;长:+经度);
}
}捕获(IOE异常)
{
e、 printStackTrace();
}
}
//----------|主要|-----------------------------
公共静态void main(字符串[]args)
{
LatLong app=新的LatLong();
//写
Path pathOutput=Path.get(“/Users/basilbourque/lat long.csv”);
app.write(pathOutput);
System.out.println(“写入文件:“+pathOutput”);
//阅读
Path pathInput=Path.get(“/Users/basilbourque/lat long.csv”);
app.read(路径输入);
System.out.println(“完成对lat-long数据文件的写入和读取。”+Instant.now());
}
}
非常感谢。就像一个符咒一样工作。@user1425223请注意,String.split
需要一个正则表达式,如果您想确保没有任何有趣的事情发生(比如
或|
),您可以首先通过Pattern.quote()
:str.split(Pattern.quote(“.”)
(或手动转义)@AVD::您在文本文件中得到上面显示的第一行了吗?我无法得到第一行的内容…rest都很好。@user3560140该代码片段解释了Split
方法的用法。如果您的代码有问题,请问一个新问题。@AVD:我想解决方案是从文本文件中读取逗号分隔的值?这是不正确的。读取它时,并不是读取该文本文件中的第一个值。因此,如果有人以此为例,他将不必要地遇到问题。这就是原因如果您喜欢使用comment.OpenCSV,那么通过comment.OpenCSV打开它是一个流行的库。这里的细节:还有一些关于类似主题的其他stackoverflow问题:-小数点后14位是
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() );
}
}