在java中创建文本文件并以unix格式保存 [英] creating text file and saving in unix format in java

查看:188
本文介绍了在java中创建文本文件并以unix格式保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写java代码才能在Unix环境下进行文件操作.由于需要处理文件,如何在Java中创建和保存Unix格式的文件?

I need to write java code to be able to work in Unix environment for file operations. As I need to deal with files, how do I create and save a file in Unix format in Java?

推荐答案

Unix 格式"只是一个文本文件,表示 行结尾\n 而不是 \n\r (Windows) 或 \r (Mac 之前的 OSX).

"Unix format" is simply a text file that denotes line endings with \n instead of \n\r (Windows) or \r (Mac before OSX).

这是基本思想;写每一行,后跟一个显式的 \n(而不是 .newLine() 这是平台相关的):

Here's the basic idea; write each line, followed by an explicit \n (rather than .newLine() which is platform-dependent):

public static void writeText(String[] text){
  Path file = Paths.get("/tmp/filename");
  try (BufferedWriter bw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
    for(String s : text){
      bw.write(s);
      bw.write("\n");
    }
  } catch (IOException e) {
    System.err.println("Failed to write to "+file);
  }
}

这篇关于在java中创建文本文件并以unix格式保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆