尝试读取文本文件并将内容添加到数组列表中,而不是写入新的文本文件,但是其显示格式与原始文件不同。 我希望它的格式与原始文件相同。
public static void main(String args[]) throws IOException
{
Scanner sc1 = new Scanner(new File("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\sample1-pp.txt"));
ArrayList<String> list = new ArrayList<String>();
//testing
FileWriter writer = new FileWriter ("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\output.txt");;
if(!sc1.hasNext())
{
System.out.println("File is empty");
}
try {
while (sc1.hasNext())
{
list.add(sc1.nextLine().trim().toLowerCase().replaceAll("\\p{P}", ""));
}
sc1.close();
//for testing
for(String str: list)
{
writer.write(str);
}
writer.close();
傲慢与偏见
简·奥斯丁
第1章
一个公认的事实是,一个拥有好运的单身男人必须缺少妻子。
======
骄傲与偏见,简·奥斯特安珀特(Jane Austenchapter)1,这是一个公认的真理,一个拥有好运的单身男人必须缺少妻子
答案 0 :(得分:0)
为什么您从文件中读取行,将它们转换为小写,修剪它们然后将它们添加到ArrayList ...? 只需按原样向ArrayList添加行
public static void main(String args[]) {
try {
Scanner sc1 = new Scanner(new File("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\sample1-pp.txt"));
ArrayList<String> list = new ArrayList<String>();
//testing
FileWriter writer = new FileWriter("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\output.txt");;
if (!sc1.hasNext()) {
System.out.println("File is empty");
}
while (sc1.hasNext()) {
list.add(sc1.nextLine());
}
sc1.close();
//for testing
for (String str : list) {
writer.write(str);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
写入文件时需要添加行分隔符
public static void main(String args[]) throws IOException{
Scanner sc1 = new Scanner(new File("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\sample1-pp.txt"));
ArrayList<String> list = new ArrayList<String>();
//testing
FileWriter writer = new FileWriter ("C:\\Users\\amank\\eclipse-workspace\\DataStructures\\src\\output.txt");;
if(!sc1.hasNext())
{
System.out.println("File is empty");
}
try {
while (sc1.hasNext())
{
list.add(sc1.nextLine().trim().toLowerCase().replaceAll("\\p{P}", ""));
}
sc1.close();
//for testing
String newLine = System.getProperty("line.separator");
for(String str: list)
{
writer.write(str+newLine);
}
writer.close();