我正在尝试将包含节点数据(主要是 p 值)的 .csv 文件读入我的程序,但这样做时我必须将它们从字符串转换为 double 。其方法如下:
public ArrayList<Node> getCSVFile(String file){
String csvFile = file;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Node> nL = new ArrayList<Node>();
int count = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] node = line.split(cvsSplitBy);
double pVal = Double.parseDouble(node[4]);
nL.add(new Node(count, node[0], pVal));
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nL;
}
对象 Node 被参数化为 Node(int, String, double),但我尝试转换的文件的第一行是列名,我不完全确定之后条目的性质。看一下文件的开头:
GENE,COMMON,gal1RGexp,gal4RGexp,gal80Rexp,gal1RGsig,gal4RGsig,gal80Rsig YHR051W,COX6,-0.034,0.111,-0.304,3.75720e-01,1.56240e-02,7.91340e-06 YHR124W,NDT80,-0.090,0.007,-0.348,2.71460e-01,9.64330e-01,3.44760e-01 YKL181W,PRS1,-0.167,-0.233,0.112,6.27120e-03,7.89400e-04,1.44060e-01 YGR072W,UPF3,0.245,-0.471,0.787,4.10450e-04,7.51780e-04,1.37130e-05 YHL020C,OPI1,0.174,-0.015,0.151,1.40160e-04,7.19120e-01,1.53950e-02 YGR145W,YGR145W,0.387,-0.577,-0.088,5.37920e-03,8.27330e-03,7.64180e-01 YGL041C,YGL041C,0.285,-0.086,0.103,4.46050e-04,4.50790e-01,7.03040e-01 YGR218W,CRM1,-0.018,-0.001,-0.018,6.13810e-01,9.79400e-01,8.09690e-01 YOR202W,HIS3,-0.432,-0.710,0.239,1.09790e-02,1.79790e-04,5.48950e-03 YCR005C,CIT2,0.085,0.392,0.464,4.18980e-02,1.53050e-06,2.74360e-06 YER187W,KHS1,0.159,0.139,-0.045,8.51260e-04,4.17830e-03,6.18020e-01 YBR026C,YBR026C,0.276,0.189,0.291,3.63320e-05,6.15230e-04,1.24430e-03 YMR244W,YMR244W,0.078,-0.239,-0.072,5.76050e-01,3.55240e-01,8.85690e-01 Etc etc..
因此,代码根据第一列和第五列以及唯一的计数器为每行创建节点。但是,如何跳过只有列名的第一行?我有点犹豫是否要简单地跳过所有文件中的所有第一行,因为并非所有读取的文件都可能将字符串作为第一行。即使如此,以下行是否适合转换为 double ?
谢谢!
最佳答案
当无法解析 double 时,如何跳过行? 像这样:
public ArrayList<Node> getCSVFile(String file){
String csvFile = file;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Node> nL = new ArrayList<Node>();
int count = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] node = line.split(cvsSplitBy);
double pVal;
try {
pVal = Double.parseDouble(node[4]);
} catch (NumberFormatException e) {
continue; // Skip this line if this isn't a double
}
nL.add(new Node(count, node[0], pVal));
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nL;
}
关于java - 读取 p 值的 .csv 文件,如何忽略/转换某些输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27557761/