简体   繁体   中英

System.getProperty(line.separator) error

I'm a java student and this example is from the textbook. The problem I'm having is line.separator isn't putting the record on the next line. The result, at the bottom, is what it's doing. It's putting the records on the same row. The book shows the output the way it should be. I copy and paste the code into Eclipse and Notepad and run it. I get the same result both ways. Thanks in advance for any assistance.

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);
    }
}

}

result: 000, ,00.00 001,Greg Look002,John Smit003,Fred Flint,2541.02

000, ,00.00 000, ,00.00 etc

try change this line.

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM