Is there a way to write integer to a file in java

一个人想着一个人 提交于 2019-12-25 07:13:06

问题


I have a program that converts Excel to CSV and I used 2 ways to do this: one of them uses CsvWriter write and the other program uses BufferedWriter write but the problem that I have encountered here is in order to write an Integer to a file you need to convert it to string with

String.valueOf(myInt);

but I need a pure Integer not a string because when I am trying to upload this file in Oracle database it throws me

Ora-01722 invalid number exception

I tried to create a CSV file from my Windows and Oracle works perfectly fine with that data.

So my question is there a way to write an Integer not a String to a file? Any help?


回答1:


Use DataOutputStream Object to write primitive int value to a file.

Example:

 //create FileOutputStream object
   FileOutputStream fos = new FileOutputStream(strFilePath);

/*
 * To create DataOutputStream object from FileOutputStream use,
 * DataOutputStream(OutputStream os) constructor.
 */

   DataOutputStream dos = new DataOutputStream(fos);

   int i = 100;

/*
 * To write an int value to a file, use
 * void writeInt(int i) method of Java DataOutputStream class.
 *
 * This method writes specified int to output stream as 4 bytes value.
 */

   dos.writeInt(i);

/*
 * To close DataOutputStream use,
 * void close() method.
 *
 */

   dos.close();



回答2:


One option is to use a DataOutputStream (resp. DataInputStream) to write (resp. read) any primitive Java type to or from a file.



来源:https://stackoverflow.com/questions/32650143/is-there-a-way-to-write-integer-to-a-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!