简体   繁体   English

使用Java写入文件

[英]Writing Into a file using Java

 public static void writeIntoFile() {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("Employee.txt");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(list1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream == null) {
                System.out.println("file is not created");
            }
            if (objectOutputStream == null) {
                System.out.println("cant able to write");
            }
        }
    }

I want to using this function to writing in a file. 我想使用此功能写入文件。 it writes successfully but it display data in bytecode. 它写入成功,但以字节码显示数据。 how can I save it into string format? 如何将其保存为字符串格式?

Use a FileWriter wrapped inside a BufferedWriter to write character data to a File . 使用包裹在BufferedWriterFileWriter将字符数据写入File

ObjectOutputStream is used for serialization and results in a binary encoded file. ObjectOutputStream用于序列化,并生成二进制编码的文件。 Its only useful if you only want to load the file through your program and do not wish to read its contents elsewhere like in an external editor. 仅当您只想通过程序加载文件并且不希望在外部编辑器中读取其内容时,它才有用。

You also need to iterate through your List and save the requisite properties of your underlying Object in a format you wish to parse your File later on in. For example, as CSV (comma separated values) every Employee object and its properties would be persisted as one single line in the output file. 您还需要通过你的迭代List并保存潜在的必要属性Object中要解析的格式File后来在,例如,如CSV(逗号分隔值)每一个Employee对象及其属性将坚持为输出文件中的一行。

BufferedWriter br = new BufferedWriter(new FileWriter("Employee.csv"));
for (Employee employee : list) {
    br.write(employee.getFName() + ", " + employee.getLName());
    br.newLine();
}
br.close();

in the function writeIntoFile is write a Serialization Object into file 在函数writeIntoFile中将序列化对象写入文件

you should use the object's toString() to write a String into file 您应该使用对象的toString()将字符串写入文件

you can change bytecode into string using one simple way. 您可以使用一种简单的方法将字节码更改为字符串。 pass the bytecode into string constructor like this: 将字节码传递给字符串构造函数,如下所示:

new String(bytecode object); 新的String(字节码对象);

and then write string object into file. 然后将字符串对象写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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