【问题标题】:Printing a Hashset of Strings on seperate lines [duplicate]在单独的行上打印字符串的哈希集[重复]
【发布时间】:2013-11-15 11:31:50
【问题描述】:

我已将 txt 文件读入 Arraylist 以对其进行格式化,然后将该列表读入 Hashset 以删除重复项。当我尝试写入 txt 文件时,它会将所有值放在一行上。如果我尝试将 ArrayList 写入 txt 文件,它将分隔行。欢迎任何帮助

public static void main(String[] args)
{
 String filename = "data.txt";
 String filename_out = "output.txt";
 boolean dataRead;
 ArrayList<String> textFile = new ArrayList<String>();

try{

         Scanner datafile = new Scanner(new FileReader(filename));

        while(datafile.hasNext()) {
            //Scanner readIn = new Scanner(datafile.next());//.useDelimiter("[,;:.!? ]") ;

            textFile.add (datafile.next().replaceAll("\\p{Punct}|\\d","").toLowerCase().trim()); //reads next line, removes punctuation, sets to lowercase

    }

   // Collections.sort(textFile); // sort into alphabetical order
    datafile.close();
    dataRead = true;

}
 catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

ArrayList<String> dictionary = new ArrayList<String>();
Set<String> s = new HashSet<String>(textFile);
for (String eachString : s)
{
    dictionary.add(eachString);
}
Collections.sort(dictionary);
//System.out.println(dictionary);

try{
FileWriter fw = new FileWriter(filename_out);
Writer output = new BufferedWriter(fw);
int listSize = dictionary.size();
for (int i = 0; i < listSize; i++){
    output.write(dictionary.get(i).toString()+ "\n"); //this is where i think the problem is
}

output.close();
    } 
     catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }        

}

【问题讨论】:

  • 我认为这个答案应该会有所帮助。 stackoverflow.com/a/8491808/728610
  • @ArvindSridharan:当您看到已回答的问题时,请将问题标记为重复。
  • 哦,对了。我现在已经标记了它。

标签: java newline hashset


【解决方案1】:

Windows 使用\r\n

所以改变

output.write(dictionary.get(i).toString()+ "\n"); 

output.write(dictionary.get(i).toString()+ "\r\n"); 

【讨论】:

  • 谢谢!这有效!
【解决方案2】:

输出一个 BufferedWriter 并使用它的 newLine() 方法。

BufferedWriter output = new BufferedWriter(fw);

...
output.write(dictionary.get(i).toString());
output.newLine();
...

【讨论】:

    【解决方案3】:

    试试这个

    output.write(dictionary.get(i).toString()+System.getProperty("line.separator"));
    

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 2022-06-15
      • 2023-03-15
      • 2019-07-16
      • 2017-02-02
      相关资源
      最近更新 更多