java怎样从txt文件中有选择的读取数据存入数组,且每个数据项(有汉字或数字)之间用逗号隔开?

2024-12-04 05:33:53
推荐回答(1个)
回答(1):

//写了一会儿呢。。给点辛苦分铅慎吧
package com.secondDay;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class Test1 {
/宽激链**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test1().getFile("D:\\haha.txt","D:\\WUWUWU.txt");
}
public void getFile(String path,String path1){
File file = new File(path);
FileInputStream fis = null;
String readStr;
String[] str = null;
StringBuffer sb = new StringBuffer();
StringBuffer sb1 = new StringBuffer();
if(file.exists()){
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((readStr=br.readLine())!=null){
sb.append(readStr+"\n");
}
System.out.println(sb.toString());
str = sb.toString().split("\n");
if(null==str){
throw new Exception("获取异常!");
}
for(int i=0;i String[] chgStr = str[i].split(",");
sb1.append(chgStr[0]+"Z\n");
}
System.out.println(sb1.toString());
this.write(sb1.toString(), path1);
} catch (FileNotFoundException e) {
//慎孙 TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
throw new Exception("文件不存在!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void write(String text,String path){
FileOutputStream fos = null;
if(!"".equals(text.trim())){
try {
fos = new FileOutputStream(path);
fos.write(text.getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}