日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java实现栅格数据格式文件读取及加法操作

發(fā)布時間:2025/3/21 java 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java实现栅格数据格式文件读取及加法操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

問題:

? ? ? 現(xiàn)在有兩個包含柵格數(shù)據(jù)的txt文件dem1.txt、dem2.txt,要實現(xiàn)對兩個文件的讀取,并且將兩個文件中的數(shù)據(jù)對應(yīng)相加,輸出結(jié)果。文件格式如下:? ? ?

步驟:

1.通過InputStream讀取數(shù)據(jù),用字節(jié)數(shù)組存貯,再將字節(jié)數(shù)組轉(zhuǎn)為字符串;

2.字符串按換行符分割,再將每行按空格分割,分割后的數(shù)據(jù)轉(zhuǎn)為整型存儲到二維數(shù)組;

3.將兩個二維數(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{//先定義一個字節(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。