输入和输出文件都是以\t分割的txt文件,每一行是一组数据(xi)
例如
24 42 9 8 3 4 39 43
23 43 5 54 5 32 25 54
52 54 43 53 55 2 5 5
对于第i行(该行的每个归一化后的数据=(初始数据-该行最小值)/(该行最大值-该行最小值))
归一化后xij = (xij-min)/(max-min)
import java.io.*;
import java.net.URI;
import java.nio.file.FileSystem;
import java.util.ArrayList;
public class Guiyihua {
public static void main(String[] args) throws Exception {
String oldPath = "C:\\Users\\hong\\Desktop\\electric.txt";
String newPath = "C:\\Users\\hong\\Desktop\\new\\electric.txt";
ArrayList<ArrayList<Double>> data =getFile(oldPath);
double max;
double min;
double temp;
double a;
for (ArrayList<Double> datum : data) {
max = getMax(datum);
min = getMin(datum);
for (int j = 0; j < datum.size(); j++) {
temp =datum.get(j);
a = (temp - min) / (max - min);
datum.set(j,a);
}
}
out(newPath,data);
}
//获取ArrayList<Double> dataone中的最大值
public static Double getMax(ArrayList<Double> dataone){
double max = dataone.get(0);
for (Double aDouble : dataone) {
if (max < aDouble) {
max = aDouble;
}
}
return max;
}
//获取ArrayList<Double> dataone中的最小值
public static Double getMin(ArrayList<Double> dataone){
double min = dataone.get(0);
for (Double aDouble : dataone) {
if (min > aDouble) {
min = aDouble;
}
}
return min;
}
//读取txt文件并且写入ArrayList<ArrayList<Double>>
private static ArrayList<ArrayList<Double>> getFile(String pathName) throws Exception {
File file = new File(pathName);
if (!file.exists())
throw new RuntimeException("Not File!");
BufferedReader br = new BufferedReader(new FileReader(file));
String str;
ArrayList<ArrayList<Double>> data = new ArrayList<>();
while ((str = br.readLine()) != null) {
ArrayList<Double> oneData = new ArrayList<>();
String[] arr = str.split("\t");
for (String s : arr) {
oneData.add(Double.valueOf(s));
}
data.add(oneData);
}
return data;
}
//输出
public static void out(String path,ArrayList<ArrayList<Double>> data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(path));
for (int i = 0; i <data.size() ; i++) {
for (int j = 0; j < data.get(i).size(); j++) {
writer.write(String.valueOf(data.get(i).get(j)));
writer.write('\t');
}
writer.write('\n');
}
}
}