Java读取包含坐标位置或经纬度的txt文件(2021.1.4)

1、环境准备

        Java对应JDK版本号:1.8.0_221

        编程IDE选择的是Eclipse,当然也可以选择记事本Notepad或IDEA、MyEclipse等。

2、txt文件数据格式

        1.txt:每行对应一个点,可以是点的X、Y坐标,也可以是点对应的经度Lon、纬度Lat,分割符为‘,’)

120.103,29.045
101.301,24.141
85.658,42.002
89.116,31.101
120.951,23.657
102.897,30.277
108.765,34.115
112.383,37.699
118.430,36.178
96.477,35.723
105.985,37.366
111.072,41.386
123.516,41.474
115.634,27.735
126.450,43.501
111.579,28.016
113.030,30.900
127.887,46.770
113.585,33.800
116.444,40.222
117.349,39.221
109.775,19.222
106.611,26.668
108.411,23.015
103.797,35.949
118.025,26.004
117.188,32.014
121.681,31.214
107.765,29.800
119.966,32.472
113.358,23.277
115.403,38.222

在这里插入图片描述

3、编写Java类

3.1 类中所用到的方法Method

3.1.1 获取txt文件行数的函数

public static int GetRowCount1(String txtpath)
    {
    
    
    	File file = new File(txtpath);
    	int rowcount=0;
        if(file.isFile() && file.exists())
        {
    
    
            try 
            {
    
    
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String text = null;
                while((text = bufferedReader.readLine()) != null)
                {
    
    
                	rowcount++;
                }
                bufferedReader.close();
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
		return rowcount;
    }

3.1.2 读取txt文件坐标到二维数组的函数

public static void ReadTxt1(String txtPath,double[][] p) //读取txt中的经纬度并赋值给Point数组
    {
    
    
        File file = new File(txtPath);
        if(file.isFile() && file.exists())
        {
    
    
            try 
            {
    
    
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String text = null;
                int i=0,k=0;
                while((text = bufferedReader.readLine()) != null)
                {
    
    
                	String row = "";//获取读取的行字符串
        			for(int j=0;j<text.length();j++)
        				if(text.charAt(j) != '\0') 
        					{
    
    
        						row +=text.charAt(j);
        					}      	
            		String[] s = row.split(",");
            		p[k][0]=Double.parseDouble(s[0]); p[k][1]=Double.parseDouble(s[1]);
            		k++;
                	i++;
                }
                bufferedReader.close();
            } catch (Exception e) 
            {
    
    
                e.printStackTrace();
            }
        }
    }

3.1.3 保存点的二维数组到TXT文件函数

public static void WriteTxt(String txtPath,double[][] p){
    
        
    	FileWriter fileWriter = null;
		try {
    
    
			fileWriter = new FileWriter(txtPath);//创建文本文件
			for(int i=0;i<p.length;i++)
			{
    
    
				if(i == p.length -1) fileWriter.write(p[i][0]+","+p[i][1]);
				else fileWriter.write(p[i][0]+","+p[i][1]+"\r\n");
			}
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
     }

3.1.4 主函数main

public static void main(String[] args)
	{
    
    
		String readtxtfilepath = "D:\\Program Files (x86)\\eclipse2019\\EclipseWorkspace\\TestURLRequest\\src\\com\\test\\1.txt";
		String writetxtfilepath = "D:\\Program Files (x86)\\eclipse2019\\EclipseWorkspace\\TestURLRequest\\src\\com\\test\\2.txt";
		int n=GetRowCount1(readtxtfilepath);
		System.out.println("共有"+n+"条数据");
		double[][] mypoint = new double[n][2];
		for(int i=0;i<n;i++)
			{
    
    
			   mypoint[i][0]=0;
			   mypoint[i][1]=0;
			}
		ReadTxt1(readtxtfilepath, mypoint);
		System.out.println("Hello World!");
		WriteTxt(writetxtfilepath,mypoint);
		for(int i=0;i<n;i++)
			System.out.println((i+1)+":["+mypoint[i][0]+","+mypoint[i][1]+"]");
	}

3.2 涉及到的字符串知识

获取文件中的一行字符串String text = bufferedReader.readLine();//读取txt文件中的一行数据
Java中单个字符为空的表示'\0'
获取字符串中字符的个数text.length()
从字符串中获得单个字符text.charAt(j) //获取字符串text中的第(j+1)个字符
单个字符连接为字符串String row = ""; row +=text.charAt(j);//在字符串后添加单个字符可以用+
利用分割符将字符串拆分为字符串数组String[] s = row.split(",");//字符串数组
字符串转换为Double后赋给二维数组p[k][0]=Double.parseDouble(s[0]); p[k][1]=Double.parseDouble(s[1]);//二维数组p中0对应X坐标或经度Lon、1对应Y坐标或纬度Lat

3.2 完整Java类代码MakeData.java

        MakeData.java

package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class MakaData
{
    
    

    /*public static void ReadTxt(String txtPath,double[][] p) //读取txt中的经纬度并赋值给Point数组
    {
        File file = new File(txtPath);
        if(file.isFile() && file.exists())
        {
            try 
            {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String text = null;
                int i=0,k=0;
                while((text = bufferedReader.readLine()) != null)
                {
                	if(i%2==0)//偶数行才管用
                	{
                    	String row = "";//获取读取的行字符串
                    	int count=0;
                		if(i == 0)
                		{
                			for(int j=0;j<text.length();j++)
                				if(text.charAt(j) == ',' || text.charAt(j) == '.' || (text.charAt(j) >='0' && text.charAt(j) <='9')) 
                					{
                						row+=text.charAt(j);
                					}
                		}
                		else
                		{
                			for(int j=0;j<text.length();j++)
                				if(text.charAt(j) != '\0') 
                					{
                						//System.out.print(text.charAt(j));
                						row +=text.charAt(j);
                					}
                		}
                		String[] s = row.split(",");
                		p[k][0]=Double.parseDouble(s[0]); p[k][1]=Double.parseDouble(s[1]);
                		k++;
                	}
                	i++;
                }
                bufferedReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static int GetRowCount(String txtpath)
    {
    	File file = new File(txtpath);
    	int rowcount=0;
        if(file.isFile() && file.exists())
        {
            try 
            {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String text = null;
                while((text = bufferedReader.readLine()) != null)
                {
                	rowcount++;
                }
                bufferedReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
		return rowcount/2+1;
    }*/
    
    public static void WriteTxt(String txtPath,double[][] p){
    
        
    	FileWriter fileWriter = null;
		try {
    
    
			fileWriter = new FileWriter(txtPath);//创建文本文件
			for(int i=0;i<p.length;i++)
			{
    
    
				if(i == p.length -1) fileWriter.write(p[i][0]+","+p[i][1]);
				else fileWriter.write(p[i][0]+","+p[i][1]+"\r\n");
			}
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
     }
    public static int GetRowCount1(String txtpath)
    {
    
    
    	File file = new File(txtpath);
    	int rowcount=0;
        if(file.isFile() && file.exists())
        {
    
    
            try 
            {
    
    
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String text = null;
                while((text = bufferedReader.readLine()) != null)
                {
    
    
                	rowcount++;
                }
                bufferedReader.close();
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
		return rowcount;
    }
    public static void ReadTxt1(String txtPath,double[][] p) //读取txt中的经纬度并赋值给Point数组
    {
    
    
        File file = new File(txtPath);
        if(file.isFile() && file.exists())
        {
    
    
            try 
            {
    
    
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String text = null;
                int i=0,k=0;
                while((text = bufferedReader.readLine()) != null)
                {
    
    
                	String row = "";//获取读取的行字符串
        			for(int j=0;j<text.length();j++)
        				if(text.charAt(j) != '\0') 
        					{
    
    
        						row +=text.charAt(j);
        					}      	
            		String[] s = row.split(",");
            		p[k][0]=Double.parseDouble(s[0]); p[k][1]=Double.parseDouble(s[1]);
            		k++;
                	i++;
                }
                bufferedReader.close();
            } catch (Exception e) 
            {
    
    
                e.printStackTrace();
            }
        }
    }
	public static void main(String[] args)
	{
    
    
		String readtxtfilepath = "D:\\Program Files (x86)\\eclipse2019\\EclipseWorkspace\\TestURLRequest\\src\\com\\test\\1.txt";
		String writetxtfilepath = "D:\\Program Files (x86)\\eclipse2019\\EclipseWorkspace\\TestURLRequest\\src\\com\\test\\2.txt";
		int n=GetRowCount1(readtxtfilepath);
		System.out.println("共有"+n+"条数据");
		double[][] mypoint = new double[n][2];
		for(int i=0;i<n;i++)
			{
    
    
			   mypoint[i][0]=0;
			   mypoint[i][1]=0;
			}
		//ReadTxt(readtxtfilepath, mypoint);
		ReadTxt1(readtxtfilepath, mypoint);
		System.out.println("Hello World!");
		WriteTxt(writetxtfilepath,mypoint);
		for(int i=0;i<n;i++)
			System.out.println((i+1)+":["+mypoint[i][0]+","+mypoint[i][1]+"]");
	}
}

3.3 运行结果

        Eclipse中执行结果:
在这里插入图片描述
        最终将1.txt中读取到的坐标写到了2.txt中,结果如下:
在这里插入图片描述
在这里插入图片描述

4、其他一些坐标格式

4.1 格式一 i:[x,y]

1:[120.103,29.045]
2:[101.301,24.141]
3:[85.658,42.002]
4:[89.116,31.101]
5:[120.951,23.657]
6:[102.897,30.277]
7:[108.765,34.115]
8:[112.383,37.699]
9:[118.43,36.178]
10:[96.477,35.723]
11:[105.985,37.366]
12:[111.072,41.386]
13:[123.516,41.474]
14:[115.634,27.735]
15:[126.45,43.501]
16:[111.579,28.016]
17:[113.03,30.9]
18:[127.887,46.77]
19:[113.585,33.8]
20:[116.444,40.222]
21:[117.349,39.221]
22:[109.775,19.222]
23:[106.611,26.668]
24:[108.411,23.015]
25:[103.797,35.949]
26:[118.025,26.004]
27:[117.188,32.014]
28:[121.681,31.214]
29:[107.765,29.8]
30:[119.966,32.472]
31:[113.358,23.277]
32:[115.403,38.222]

        这种格式可以考虑将各行读取为一个字符串,然后截取[]之间的字符串,对该字符串利用逗号分隔符分为两个字符串,每个字符串转为double后赋值给x和y。

String text = bufferedReader.readLine();
int index1 = text.indexOf('[');//获取左中括号的索引
int index2 = text.indexOf(']');//获取右中括号的索引
String result = text.substring(index1 + 1, index2 - index1);//利用substring函数截取中括号内的字符串
String[] s = result.split(",");//利用逗号分隔符将字符串分为两个字符串
p[k][0]=Double.parseDouble(s[0]); p[k][1]=Double.parseDouble(s[1]);//第一个字符串转换为double赋给x坐标或经度Lon,第二个字符串转换为double赋给y坐标或纬度Lat

4.2 格式二 {lng: x, lat: y},

{
    
    lng: 120.103, lat: 29.105},
{
    
    lng: 101.301, lat: 24.141},
{
    
    lng: 85.658, lat: 42.002},
{
    
    lng: 89.116, lat: 31.101},
{
    
    lng: 120.951, lat: 23.657},
{
    
    lng: 102.897, lat: 30.277},
{
    
    lng: 108.765, lat: 34.115},
{
    
    lng: 112.383, lat: 37.699},
{
    
    lng: 118.430, lat: 36.178},
{
    
    lng: 96.477, lat: 35.723},
{
    
    lng: 105.985, lat: 37.366},
{
    
    lng: 111.072, lat: 41.386},
{
    
    lng: 123.516, lat: 41.474},
{
    
    lng: 115.634, lat: 27.735},
{
    
    lng: 126.450, lat: 43.501},
{
    
    lng: 111.579, lat: 28.016},
{
    
    lng: 113.030, lat: 30.900},
{
    
    lng: 127.887, lat: 46.770},
{
    
    lng: 113.585, lat: 33.800},
{
    
    lng: 116.444, lat: 40.222},
{
    
    lng: 117.349, lat: 39.221},
{
    
    lng: 109.775, lat: 19.222},
{
    
    lng: 106.611, lat: 26.668},
{
    
    lng: 108.411, lat: 23.015},
{
    
    lng: 103.797, lat: 35.949},
{
    
    lng: 118.025, lat: 26.004},
{
    
    lng: 117.188, lat: 32.014},
{
    
    lng: 121.681, lat: 31.214},
{
    
    lng: 107.765, lat: 29.800},
{
    
    lng: 119.966, lat: 32.472},
{
    
    lng: 113.358, lat: 23.277},
{
    
    lng: 115.403, lat: 38.222}]

        这种格式可以考虑对读取的每行字符串,首先利用{}截取字符串,然后利用逗号分隔符划分为两个字符串,对第一个字符串截取lng: 以后的部分,对第二个字符串截取lat: 以后的部分,对两个部分各自转为double后即可赋值给点的x、y坐标或经度Lon和纬度Lat。

String text = bufferedReader.readLine();
int index1 = text.indexOf('{');//获取左中括号的索引
int index2 = text.indexOf('}');//获取右中括号的索引
String result = text.substring(index1 + 1, index2 - index1);//利用substring函数截取中括号内的字符串
String[] s = result.split(",");//利用逗号分隔符将字符串分为两个字符串
index1 = s[0].indexOf(':');//获取lng:后空格的索引
index2 = s[1].indexOf(':');//获取lat:后空格的索引
String s1 = s[0].substring(index1+2),s2 = s[1].substring(index2+2);
p[k][0]=Double.parseDouble(s1); p[k][1]=Double.parseDouble(s2);//第一个字符串转换为double赋给x坐标或经度Lon,第二个字符串转换为double赋给y坐标或纬度Lat

猜你喜欢

转载自blog.csdn.net/jing_zhong/article/details/112175418