Java System.getProperty(line.separator)错误

Java System.getProperty(line.separator)错误,java,Java,我是一名java学生,这个例子来自教科书。我遇到的问题是line.separator没有将记录放在下一行。结果,在底部,就是它在做什么。它把记录放在同一行。这本书以应有的方式展示了输出。我将代码复制并粘贴到Eclipse和记事本中,然后运行它。我两方面都得到相同的结果。提前感谢您的帮助 import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer

我是一名java学生,这个例子来自教科书。我遇到的问题是line.separator没有将记录放在下一行。结果,在底部,就是它在做什么。它把记录放在同一行。这本书以应有的方式展示了输出。我将代码复制并粘贴到Eclipse和记事本中,然后运行它。我两方面都得到相同的结果。提前感谢您的帮助

import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;

public class CreateEmployeesRandomFile {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Path file = Paths.get("C:\\EJava\\Employee.txt");

    String s = "000, ,00.00" + System.getProperty("line.separator");
    final int RECSIZE = s.length();
    FileChannel fc = null;
    String delimiter = ",";
    String idString;
    int id;
    String name;
    String payRate;
    final String QUIT = "999";
    try {
        fc = (FileChannel) Files.newByteChannel(file, CREATE, WRITE);
        System.out.print("Enter employee ID number >> ");
        idString = input.nextLine();
        while (!(idString.equals(QUIT))) {
            id = Integer.parseInt(idString);
            System.out.print("Enter name for employee #" + id + " >> ");
            name = input.nextLine();
            System.out.print("Enter pay rate >> ");
            payRate = input.nextLine();
            s = idString + delimiter + name + delimiter + payRate
                    + System.getProperty("line.separator");
            byte[] data = s.getBytes();
            ByteBuffer buffer = ByteBuffer.wrap(data);
            fc.position(id * RECSIZE);
            fc.write(buffer);
            System.out.print("Enter next ID number or " + QUIT
                    + " to quit >> ");
            idString = input.nextLine();
        }
        fc.close();
    } catch (Exception e) {
        System.out.println("Error message: " + e);
    }
}
}

结果: 000,00.00 001,格雷格·洛克002,约翰·斯密特003,弗雷德·弗林特,2541.02

000,00.00 000, ,00.00 etc

尝试更改此行

fc = (FileChannel) Files.newByteChannel(file, CREATE, WRITE);


它依赖于操作系统。线分离器在那里;也许问题在于您用来查看文本的程序:Windows记事本。世界上所有其他程序都将接受三个最常用的换行符中的任意一个:“\n”(仅限换行符)、“\r”(仅限回车符)或“\r\n”(回车符+换行符)。但是记事本只能识别“\r\n”,这是DOS/Windows系统的传统行分隔符。尝试使用记事本以外的其他工具查看文本,看看它是否有效。您使用Java jdK 7还是8?如果您有Java8,请将其更改为System.lineSeparator(),然后查看它是否有效。另一种调试方法是用OS行分隔符、Windows(“\r\n”)和字符串中的其他(“\n”)替换它,然后查看它是否出现。我尝试了这些方法,但仍在发生。我开始认为这不是这4行代码的line.separator,而是更多:byte[]data=s.getBytes();ByteBuffer缓冲区=ByteBuffer.wrap(数据);fc.位置(id*RECSIZE);fc.写入(缓冲区);很可能。尝试添加系统输出打印;在byte[]data=s.getBytes()之前,查看该字符串是否正确显示在控制台中。如果该字符串显示正确,则它们仍不会正确显示在列表中。
fc = (FileChannel) Files.newByteChannel(file, READ, WRITE);