简体   繁体   English

多行到单行

[英]multiple line to single line

FileReader f0 = new FileReader("1.html");
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(f0);
while((temp1=br.readLine())!=null)
{
sb.append(temp1);
}
String para = sb.toString().replaceAll("<br>","\n");
String textonly = Jsoup.parse(para).text();
System.out.println(textonly);

FileWriter f1=new FileWriter("1.txt");
char buf1[] = new char[textonly.length()];
textonly.getChars(0,textonly.length(),buf1,0);

for(i=0;i<buf1.length;i++)
 {
 if(buf1[i]=='\n')
  f1.write("\r\n");
 f1.write(buf1[i]);

While making the new text file this code makes multiple line and I want that the text file should have only one line. 在创建新文本文件时,此代码生成多行,我希望文本文件只有一行。 How can I do this. 我怎样才能做到这一点。

停止在文件中写入换行符\\ n,你应该停止制作多行。

Isn't <\\br> and \\n same kind of thing? 是不是<\\ br>和\\ n同样的事情? if you do this ,there will be no change in your text. 如果你这样做,你的文字就不会有变化。 You need to replace <\\br> with an space. 您需要用空格替换<\\ br>。

String para = sb.toString().replaceAll("<br>"," ");

even after removing all \\n it is making multiple lines. 即使在删除所有\\ n后,它会生成多行。

I think the error is in the following code: 我认为错误在以下代码中:

for( i = 0; i < buf1.length; i++ )
{
     if( buf1[ i ] == '\n' )
         f1.write( "\r\n" );
     f1.write( buf1[ i ] );

When a new line character \\n is matched, you are writing \\r\\n to the file and again wring the same character to the file using f1.write( buf1[ i ] ) . 当匹配新行字符\\n ,您正在将\\r\\n写入文件,并再次使用f1.write( buf1[ i ] )将相同的字符写入文件。 Using else will stop writing \\n again to the file. 使用else将停止写入\\n再次到该文件。

for( i = 0; i < buf1.length; i++ )
{
     if( buf1[ i ] == '\n' )
     {
         f1.write( "\r\n" );
     }
     else
     {
         f1.write( buf1[ i ] );
     }
     // ...
} // for

Alternatively use ternary operator to replace \\n with \\r\\n while writing. 或者使用三元运算符在写入时将\\n替换为\\r\\n

f1.write( buf1[ i ] == '\n' ? "\r\n" : buf1[ i ] );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM