System.getProperty(line.separator)错误

时间:2014-11-22 14:15:27

标签: java

我是一名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,Greg Look002,John Smit003,Fred Flint,2541.02

<00> 000,00.00 000 ,, 00.00 等

1 个答案:

答案 0 :(得分:0)

尝试更改此行。

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

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