Greetings Dear experts, please can push on the right path. Actually the task:

I need to save the file as a "file array". For example, php - this is done very simply.

file.php :

<?php return array(1,2,3); 

Is there such a possibility in java?

Looked that the ability to save objects is available.

 try (ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(new FileOutputStream(FILE))) { ObjectOutputStream.writeObject(OBJECT); } 

After saving the object, to load, I do this:

 final FileInputStream FileOutputStream = new FileInputStream(FILE); final ObjectInputStream ObjectInputStream = new ObjectInputStream(FileOutputStream); OBJECT = (ConcurrentHashMap) ObjectInputStream.readObject(); 

Is there a way to export / import arrays? As an array file, not an object.

  • one
    I don’t understand php, but what is fundamentally better than an array of objects? And why do you want to save it in him? - Artem Konovalov
  • @ArtemKonovalov array is no better and no worse than an object. It's just such an object too, conceived for storing an ordered collection of other objects. - Sergey

1 answer 1

Arrays in java are also objects. Besides the fact that an array is also an object, it is also an object that is Serializable. And like any Serializable object can be as written to a file:

 int[] arr = new int[] {1, 2, 3}; try (ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(new FileOutputStream(FILE))) { ObjectOutputStream.writeObject(arr); } 

and read from the file:

 final FileInputStream FileOutputStream = new FileInputStream(FILE); final ObjectInputStream ObjectInputStream = new ObjectInputStream(FileOutputStream); int[] arr = (int[]) ObjectInputStream.readObject(); 

Well and still array elements should be Serializable

  • better at once json / yaml / etc - etki
  • Oh, that's the thing. I didn’t even realize that we are talking about all sorts of include, which the source code is inserted with everything that is right during the work. So in java so of course it will not work. This is a compiled programming language, not a visitor counter description language. - Sergey
  • @Etki, not better. This solution is not suitable. Moreover, Sergey said correctly, although I’ve already considered this option, and I didn’t think that this is the case, it’s impossible here, just take and make return {}; in the file itself, as a strict language and pure OOP, you need to work directly from the file and save only plain files or a specific class — enum to import, again into the class or into the main Class main method. just a fragment of the script code, does not reproduce and does not even compile. - And
  • @And how are return and json related and why is it not suitable if only the serialization format changes? - etki
  • @Etki, is not suitable for my architecture, since the arrays are native, it is easier for me to tie in on this, it works much faster than large volumes. - And