Java实现栅格数据格式文件读取及加法操作
生活随笔
收集整理的這篇文章主要介紹了
Java实现栅格数据格式文件读取及加法操作
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問題:
? ? ? 現(xiàn)在有兩個(gè)包含柵格數(shù)據(jù)的txt文件dem1.txt、dem2.txt,要實(shí)現(xiàn)對兩個(gè)文件的讀取,并且將兩個(gè)文件中的數(shù)據(jù)對應(yīng)相加,輸出結(jié)果。文件格式如下:? ? ?
步驟:
1.通過InputStream讀取數(shù)據(jù),用字節(jié)數(shù)組存貯,再將字節(jié)數(shù)組轉(zhuǎn)為字符串;
2.字符串按換行符分割,再將每行按空格分割,分割后的數(shù)據(jù)轉(zhuǎn)為整型存儲(chǔ)到二維數(shù)組;
3.將兩個(gè)二維數(shù)組相加并輸出。
實(shí)現(xiàn)代碼:
import java.io.*; import java.util.ArrayList;public class DemReader {public static void main(String[] args){System.out.println("讀取柵格文件");try {InputStream dem1 = new FileInputStream(new File("D:/IdeaProjects/hello/src/data/dem1.txt"));InputStream dem2 = new FileInputStream(new File("D:/IdeaProjects/hello/src/data/dem2.txt"));String str1 = bytesToStr(dem1);String str2 = bytesToStr(dem2);dem1.close();dem2.close();int matrix1[][] = strToMatrix(str1);int matrix2[][] = strToMatrix(str2);int matrixSum[][] = new int[8][8];for(int row=0;row<matrix1.length;row++){for(int col=0;col<matrix1[0].length;col++){matrixSum[row][col] = matrix1[row][col] + matrix2[row][col];}}for (int i = 0; i < matrixSum.length; i++) {for (int j = 0; j < matrixSum[0].length; j++) {System.out.print(matrixSum[i][j]);System.out.print(" ");}System.out.println();}} catch (IOException e) {e.printStackTrace();}}//輸入流轉(zhuǎn)字符串public static String bytesToStr(InputStream is) throws IOException{//先定義一個(gè)字節(jié)數(shù)組存放數(shù)據(jù)byte[] bytes = new byte[1024];int i = 0;int index = 0;while((i=is.read())!=-1){//把讀取的數(shù)據(jù)放到i中bytes[index]=(byte) i;index++;}//把字節(jié)數(shù)組轉(zhuǎn)成字符串String str1 = new String(bytes);return str1;}//字符串轉(zhuǎn)矩陣(二維數(shù)組)public static int[][] strToMatrix(String str){String rowArr[] = str.split("\r\n");int matrix[][] = new int[8][8];int rowIndex = 0;for (String row : rowArr) {String valueArr[] = row.split("\\s+");int colIndex = 0;for (String item:valueArr) {matrix[rowIndex][colIndex] = Integer.parseInt(item.trim());colIndex++;}rowIndex++;}return matrix;} }結(jié)果輸出:
?
總結(jié)
以上是生活随笔為你收集整理的Java实现栅格数据格式文件读取及加法操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArcGIS JS先添加动态图层,再添加
- 下一篇: ArcGIS JS API 4.10跨域