lon*_*ome 14 java newline file
考虑以下功能
private static void GetText(String nodeValue) throws IOException {
if(!file3.exists()) {
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null)
fop.write(nodeValue.getBytes());
fop.flush();
fop.close();
}
Run Code Online (Sandbox Code Playgroud)
添加什么以使其在下一行中每次写入?
例如,我想要一个单独的lline中给定字符串的每个单词,例如:
i am mostafa
Run Code Online (Sandbox Code Playgroud)
写道:
i
am
mostafa
Run Code Online (Sandbox Code Playgroud)
sud*_*ode 38
要将文本(而不是原始字节)写入文件,您应该考虑使用FileWriter.您还应该将它包装在BufferedWriter中,然后BufferedWriter将为您提供newLine方法.
要在新行上写入每个单词,请使用String.split将文本分成多个单词.
所以这是对您的要求的简单测试:
public static void main(String[] args) throws Exception {
String nodeValue = "i am mostafa";
// you want to output to file
// BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
// but let's print to console while debugging
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] words = nodeValue.split(" ");
for (String word: words) {
writer.write(word);
writer.newLine();
}
writer.close();
}
Run Code Online (Sandbox Code Playgroud)
输出是:
i
am
mostafa
Run Code Online (Sandbox Code Playgroud)
Jac*_*nds 11
改变线条
if(nodeValue!=null)
fop.write(nodeValue.getBytes());
fop.flush();
Run Code Online (Sandbox Code Playgroud)
至
if(nodeValue!=null) {
fop.write(nodeValue.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
fop.flush();
Run Code Online (Sandbox Code Playgroud)
更新以解决您的编辑问题:
为了将每个单词写在不同的行上,您需要拆分输入字符串,然后分别编写每个单词.
private static void GetText(String nodeValue) throws IOException {
if(!file3.exists()) {
file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null)
for(final String s : nodeValue.split(" ")){
fop.write(s.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
}
fop.flush();
fop.close();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
Files.write(Paths.get(filepath),texttobewrittentofile,StandardOpenOption.APPEND ,StandardOpenOption.CREATE);
Run Code Online (Sandbox Code Playgroud)
如果文件不存在,则会创建一个文件(如果文件存在),它将使用现有文件并附加文本。如果要将每一行都写入下一行,请在文件中添加lineSepartor作为换行符。
String texttobewrittentofile = text + System.lineSeparator();
Run Code Online (Sandbox Code Playgroud)