[英]String to file not maintaing line breaks displays in terminal correclty java
I want to read a text file , change some text then output to a text file.我想读取一个文本文件,更改一些文本然后输出到一个文本文件。 I'd open this file in notepad
我会在记事本中打开这个文件
New to Java - This has been rehashed and posted in different way throughout the forum. Java 新手 - 这已在整个论坛中以不同的方式重新整理和发布。 They always seem to say your missing the /n in the string - I thought I did this in the below code.
他们似乎总是说您缺少字符串中的 /n - 我以为我在下面的代码中做到了这一点。
The part that is confusing to me is it displays in my terminal correctly when I use the showfile method.令我困惑的部分是当我使用 showfile 方法时它正确显示在我的终端中。
I assume its the way I'm writing the file.我假设它是我编写文件的方式。 I'd like to continue to use my method instead of the String variable
我想继续使用我的方法而不是 String 变量
Original file contains text原始文件包含文本
Bob鲍勃
Red红色的
Door门
I use this to read the text file and input it in a string.我用它来读取文本文件并将其输入到一个字符串中。
public void readFile(String fileName)
{
fileText = "";
try
{
Scanner file = new Scanner(new File(fileName));
while (file.hasNextLine())
{
String line = file.nextLine();
fileText += line +"\n";
}
file.close();
}
catch (Exception e)
{
System.out.println(e);
}
I use a method to swap all "R"s to "B"s.我使用一种方法将所有“R”交换为“B”。
I use showFile method and it displays in my terminal correctly我使用 showFile 方法,它在我的终端中正确显示
This shows correctly这显示正确
Bob鲍勃
Bed床
Door门
public String showFile()
{
return fileText;
}
But then I try output the string to a file using.但是后来我尝试使用将字符串输出到文件中。
try {
File file = new File("test1.txt");
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(startupModified.showFile());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
It keeps my spacing but I loose my line breaks它保持我的间距,但我松开了换行符
Displays:显示:
Bob Bed Door鲍勃床门
This is the constructor class for startupModified这是 startupModified 的构造函数类
public StartUpFile(String fileName)
{
readFile(fileName);
}
functions correctly now现在功能正常
changed fileText += line +"\\n";更改了文件文本 += 行 +"\\n";
to fileText += line +"\\r\\n"; to fileText += line +"\\r\\n";
I assumed it was the writer because it displayed correctly in the terminal.我认为它是作者,因为它在终端中正确显示。
Thank you谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.