我有一个文件"a.txt“,其中包含以下几行:
14,15,16,17
13,16,15,14
15,17,12,13
...
...我知道每一行总是有4列。
我必须读取这个文件,根据分隔符(这里是",")拆分行,并将每列的值写入相应的文件中,即如果列中的值是14,则必须将其转储/写入到14.txt中,如果是15,则将其写入15.txt中,依此类推。
以下是我到目前为止所做的工作:
Map <Integer, String> filesMap = new HashMap<Integer, String>();
for(int i=0; i < 4; i++)
{
filesMap.put(i, i+".txt");
}
File f = new File ("a.txt");
BufferedReader reader = new BufferedReader (new FileReader(f));
String line = null;
String [] cols = {};
while((line=reader.readLine()) != null)
{
cols = line.split(",");
for(int i=0;i<4;i++)
{
File f1 = new File (filesMap.get(cols[i]));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f1)));
pw.println(cols[i]);
pw.close();
}
}因此,对于文件"a.txt“的第1行,我必须打开、写入和关闭文件14.txt、15.txt、16.txt和17.txt
同样对于第2行,我必须再次打开、写入和关闭文件14.txt、15.txt、16.txt和一个新文件13.txt
因此,有没有更好的选择,使我不必打开和关闭之前已经打开的文件。
在完成操作结束时,我将关闭所有打开的文件。
发布于 2013-02-05 14:17:40
像这样的东西应该是有效的:
Map <Integer, PrintWriter> filesMap = new HashMap<>();
...
if(!filesMap.containsKey(cols[i]))
{
//add a new PrintWriter
} else
{
//use the existing one
}发布于 2013-02-05 14:21:28
试一试
Set<String> s = new HashSet<>();
Scanner sc = new Scanner(new File ("a.txt")).useDelimiter("[\n\r,]+");
while(sc.hasNext()) {
String n = sc.next();
if (s.add(n)) {
FileWriter w = new FileWriter(n + ".txt");
w.write(n);
w.close();
}
}
sc.close();发布于 2013-02-05 14:37:08
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("a.txt");
BufferedReader reader = new BufferedReader(fr);
String line = "";
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
for (int i = 0; i < 4; i++) {
FileWriter fstream = new FileWriter(cols[i] + ".txt" , true);// true is for appending the data in the file.
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(cols[i] + "\n");
fbw.close();
}
}
}试试这个。我认为你想这样做。
https://stackoverflow.com/questions/14701258
复制相似问题