目前我正在使用for item in range(len(shape_brightness)):
execute
来编写txt文件。代码就在这里......
java.nio.file.File.write(Path, Iterable, Charset)
但是在文本文件中生成了另外一个(第4个)空行。我怎样才能避免第4条空行?
Path filePath = Paths.get("d:\\myFile.txt");
List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine", "3. What about U ?");
Files.write(filePath, lineList, Charset.forName("UTF-8"));
答案 0 :(得分:4)
从javadoc for write:&#34;每一行都是一个char序列,按顺序写入文件,每行由平台的行分隔符终止,由系统属性line.separator。&#34;
最简单的方法:
List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine");
String lastLine = "3. What about U ?";
Files.write(filePath, lineList, Charset.forName("UTF-8"));
Files.write(filePath, lastLine.getBytes("UTF-8"), StandardOpenOption.APPEND);
答案 1 :(得分:2)
检查Files.write
您拨打的代码:
public static Path write(Path path, Iterable<? extends CharSequence> lines,
Charset cs, OpenOption... options)
throws IOException
{
// ensure lines is not null before opening file
Objects.requireNonNull(lines);
CharsetEncoder encoder = cs.newEncoder();
OutputStream out = newOutputStream(path, options);
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {
for (CharSequence line: lines) {
writer.append(line);
writer.newLine();
}
}
return path;
}
它在每个插入的末尾创建新行:
writer.newLine();
解决方案是:提供数据为byte[]
:
Path filePath = Paths.get("/Users/maxim/Appsflyer/projects/DEMOS/myFile.txt");
List<String> lineList =Arrays.asList("1. Hello", "2. I am Fine", "3. What about U ?");
String lineListStr = String.join("\n", lineList);
Files.write(filePath, lineListStr.getBytes(Charset.forName("UTF-8")));
答案 2 :(得分:0)
我愿意
Files.writeString(filePath, String.join("\n",lineList), Charset.forName("UTF-8"));