Java println:Windows 与 Linux
我有一个 java 程序,它使用 jcifs 库 -samba 内容将文件写入远程计算机文件系统; SmbFile=>SmbFileOutputStream=>PrintStream 和我使用常见的 println(String)。一切都工作正常,直到我将应用程序移至 Linux 机器,现在远程 Windows 机器上的打印文件看起来很奇怪。
我相信问题在于两个操作系统如何处理 println() 函数插入的 CR、LF 。我的“jar”每天执行一次,由“crontab”通过“sh”启动文件触发。
- 有没有办法在不接触java代码的情况下解决这个问题?
- 有没有办法编写一个java程序使其在两种操作系统(可能是所有操作系统)上运行?
谢谢
I have a java program that writes a file to a remote machine file system using the jcifs library -samba stuff; SmbFile=>SmbFileOutputStream=>PrintStream and the I use the common println(String). Everything worked fine till I moved my application to a linux machine and now the printed file on my remote windows machine looks weird.
I believe the problem is how the two OSs handle the CR, LF that are inserted by the println() function. My 'jar' is executed once a day and it's triggered by the 'crontab' through a 'sh' launch file.
- Is there a way to fix the issue without touching the java code?
- Is there a way to write a java program to make it work on both kind of OSs (possibly all of them)?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用系统属性“line.separator”。您可以阅读此内容作为参考。
Try playing around with the system property "line.separator". You can read this for reference.
您必须更改文件中的新行分隔符。在 Linux 中,有一个名为 dos2unix 的实用程序,可以将现有文件的新行分隔符从 dos 转换为/windows 到 linux/unix。
You will have to change the new line separator in the file. In linux, there is a utility called dos2unix that converts the new line separator of an existing file from dos/windows to linux/unix.
System.out.println 是一个 PrintStream,它 使用 line.separator 的环境设置一个 > 作为它,嗯,行分隔符。解决您的问题的一种方法是传入 -Dline.separator 参数。
不过,最好的解决方案可能是使用更好的编辑器查看文件。 Notepad++ 和 Windows 上的许多其他程序都可以理解这两种类型的行结尾,而记事本则不能。即使内置的写字板在显示 UNIX 文件结尾方面也能做得更好。
System.out.println is a PrintStream, which uses the environment setting for line.separator as its, well, line separator. One solution to your problem would be to pass in -Dline.separator argument.
Probably the best solution though is to just use view your file with a better editor. Notepad++ and many others on Windows will understand both types of line endings, while notepad will not. Even the builtin wordpad does a better job of displaying unix file endings.
如果你的java文件在linux机器上运行println将使用linux标准“\n”
如果您希望它始终使用 \r\n,而不更改系统属性,只需替换您的
println("文本") 与 print("文本\r\n")。或者创建一个自定义函数 printWindowsLine 来执行此操作
If your java file runs in a linux machine println will use the linux standard "\n"
If you want it to allways use \r\n, without changing system properties, simply replace your
println("text") with print("text\r\n"). Or create a custom function printWindowsLine to do that