How can I read comma separated values from a text file in Java?

后端 未结 6 778
轮回少年
轮回少年 2020-12-01 13:45

I have got this text file with latitude and longitude values of different points on a map.

How can I split my string into latitudes and longitudes? What is the gener

相关标签:
6条回答
  • 2020-12-01 13:50

    Use OpenCSV for reliability. Split should never be used for these kind of things. Here's a snippet from a program of my own, it's pretty straightforward. I check if a delimiter character was specified and use this one if it is, if not I use the default in OpenCSV (a comma). Then i read the header and fields

    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());
    }
    
    0 讨论(0)
  • 2020-12-01 13:54

    To split your String by comma(,) use str.split(",") and for tab use str.split("\\t")

        try {
            BufferedReader in = new BufferedReader(
                                   new FileReader("G:\\RoutePPAdvant2.txt"));
            String str;
    
            while ((str = in.readLine())!= null) {
                String[] ar=str.split(",");
                ...
            }
            in.close();
        } catch (IOException e) {
            System.out.println("File Read Error");
        }
    
    0 讨论(0)
  • 2020-12-01 13:54

    Use BigDecimal, not double

    The Answer by adatapost is right about using String::split but wrong about using double to represent your longitude-latitude values. The float/Float and double/Double types use floating-point technology which trades away accuracy for speed of execution.

    Instead use BigDecimal to correctly represent your lat-long values.

    Use Apache Commons CSV library

    Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.

    Example app

    Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split for the writing. And the app uses BigDecimal objects to represent your lat-long values.

    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() );
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 13:57

    You can also use the java.util.Scanner class.

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 14:00

    You may use the String.split() method:

    String[] tokens = str.split(",");
    

    After that, use Double.parseDouble() method to parse the string value to a double.

    double latitude = Double.parseDouble(tokens[0]);
    double longitude = Double.parseDouble(tokens[1]);
    

    Similar parse methods exist in the other wrapper classes as well - Integer, Boolean, etc.

    0 讨论(0)
  • 2020-12-01 14:09

    //lat=3434&lon=yy38&rd=1.0&| in that format o/p is displaying

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题