我有一個文本文件,它看起來像這樣:Java的文本文件轉換爲逗號分隔的文件
ExampleA1
ExampleA1b
ExampleA2
ExampleA2b
ExampleA3
ExampleA3b
可能有人請幫我將其轉換爲以逗號分隔,如:
ExampleA1, ExampleA1b
ExampleA2, ExampleA2b
ExampleA3, ExampleA3b
感謝您的幫助
我有一個文本文件,它看起來像這樣:Java的文本文件轉換爲逗號分隔的文件
ExampleA1
ExampleA1b
ExampleA2
ExampleA2b
ExampleA3
ExampleA3b
可能有人請幫我將其轉換爲以逗號分隔,如:
ExampleA1, ExampleA1b
ExampleA2, ExampleA2b
ExampleA3, ExampleA3b
感謝您的幫助
我可能會使用這樣的
File f = new File("temp/file.txt");
if (!f.exists()) {
return;
}
Scanner scanner = null;
List<String> al = new ArrayList<String>();
try {
scanner = new Scanner(f);
while (scanner.hasNextLine()) {
String line1 = scanner.nextLine().trim();
if (line1.length() == 0) {
continue;
}
String line2 = "";
if (scanner.hasNextLine()) {
line2 = scanner.nextLine().trim();
}
if (line2.trim().length() > 0) {
al.add(line1 + ", " + line2);
} else {
al.add(line1);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f, false);
PrintWriter pw = new PrintWriter(fos);
for (String str : al) {
pw.println(str);
}
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
與
cat file.txt
ExampleA1
ExampleA1b
ExampleA2
ExampleA2b
ExampleA3
ExampleA3b
開始,我得到這個與上述
ExampleA1, ExampleA1b
ExampleA2, ExampleA2b
ExampleA3, ExampleA3b
似乎乍一看很容易的工作,但不是那麼容易細看後:)下面是答案:
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("/home/venkatesh/Desktop/test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
int data = -1;
int prevChar = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
do {
data = reader.read();
if (data == -1) break;
if (data == '\n') {
if (prevChar == '\n') {
baos.write('\n');
prevChar = 0;
} else {
prevChar = data;
}
} else {
if (prevChar == '\n') {
baos.write(',');
baos.write(' ');
}
baos.write(data);
prevChar = data;
}
} while (true);
System.out.println(" Written Text : \n" + new String(baos.toByteArray()));
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
簡要說明:我們在這裏執行以下操作:
1.通過FileInpu打開文件tStream,然後由選定的Reader進行包裝。打開一個Outpustream(我在這裏使用了ByteArrayOutputStream來記錄簡單)。
2.使用read()API讀取char字符並檢查少數應用程序特定條件 -
a。如果currentReadChar是新行char(\ n),並且以前沒有找到新的行字符,只是跳到下一個字符(不要向輸出流寫任何東西)
b。如果currentReadChar是換行符,並且previous也是換行符,則寫一個新行字符而不是兩個字符,然後conintue爲下一個字符。 c。如果currentReadChar不是換行符char,並且previous是一個換行符char,則在寫入當前字符之前將','寫入流中
d。如果currentReadChar不是換行符,而前一個也不是換行符,寫出當前字符。
3.關閉流/讀取器並使用所需的輸出流/字符串。
基本假設:
1.有ExampleA1和ExampleA1b之間的單個新行字符
2.有例A的下一組之間的兩個新行字符...
希望這有助於...
'有人可以幫我嗎,好吧。你試過了什麼? –
[你有什麼嘗試?](http://www.whathaveyoutried.com/)我的意思是*除了*問我們。 –
查看http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html開始,嘗試獲取文本文件並將其打印出來,然後開始操作它。 – turbo