-2
嘗試從Java文件中讀取數據並將其寫入csv文件時遇到問題。我設置了一個ArrayList變量'data',使用Scanner從數據文件中讀取行。問題出現在數據被讀取並打印在這一行時:System.out.println(line);從文件中讀取文件並寫入Java文件時遇到問題
它出來是這樣的:
[Tim]
[Tim]
[March]
[Tim]
[March]
[11751 N River Dr]
[Tim]
[March]
[11751 N River Dr]
[Apt 4]
[Tim]
[March]
[11751 N River Dr]
[Apt 4]
[Mankato]
[Tim]
[March]
[11751 N River Dr]
[Apt 4]
[Mankato]
[MN]
[Tim]
[March]
[11751 N River Dr]
[Apt 4]
[Mankato]
[MN]
[56001]
當文件看起來就像這樣:
[Tim]
[March]
[11751 N River Dr]
[Apt 4]
[Mankato]
[MN]
[56001]
是否有一個原因,它是印刷線路有點不正常?我是否需要在某處添加一個循環來打印主線?我的第二個問題是,當我嘗試將該文件編寫爲CSV文件時,我遇到了打印最後一行(56001)而不是其他任何行的問題。有沒有我失蹤的事情來做到這一點?這是迄今爲止的代碼。
import java.util.*;
import java.io.*;
public class ReadFromDat {
/**
* @param <Data>
* @param args
*/
public static ArrayList<String> data;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner sc = new Scanner(new File("C:\\Users\\Tim\\Desktop\\data.dat"));
data= new ArrayList<String>();
List<String> line = null;
while (sc.hasNextLine()){
data.add(sc.nextLine());
for (String lines: data) {
line = new ArrayList<String>(Arrays.asList(lines.split("\n")));
System.out.println(line);
}
//line = Arrays.asList(data.split("\n"));
//System.out.println(data);
FileWriter output = new FileWriter("C:\\Users\\Tim\\Desktop\\data.csv");
for (String data: line) {
output.write(data);
}
output.close();
}
}
}
[瞭解如何調試。](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – shmosel