我有一个文本文件,它看起来像这样: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