- Home /
How to read data from a text file into a collection? (JSON preferred)
I need to read several lists of 2D coordinates into a data collection, like a Dictionary for example, from a text file.
I can make the file into any format (it´s originally an SVG but I made an ETL that cleans it and can spit JSON or whatever other format) but JSON is preferred. Thanks!
Answer by MaGuSware™ · Dec 24, 2012 at 04:46 PM
Well, I do it using FileStream. I first save the length of the array and then do a for loop to save the data.
Here is an example of saving an array on integers in C#
using System.IO;
public class SomeClass
{
FileStream file;
public void SaveArray(int[] arr)
{
file = File.open("myfile.format", FileMode.OpenOrCreate);
byte[] arraySize = System.BitConverter.GetBytes(arr.Length);
file.Write(arraySize, 0, sizeof(int));
for(int i = 0; i < arr.Length; i++)
{
byte[] arrayElement = System.BitConverter.GetBytes(arr[i]);
file.Write(arrayElement, 0, sizeof(int));
}
file.Close();
}
public void LoadArray(int[] arr)
{
if (file = File.Open("myfile.format", FileMode.Open))
{
byte[] arraySize = new byte[sizeof(int)];
file.Read(arraySize, 0, sizeof(int));
arr = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
byte[] arrayElement = new byte[sizeof(int)];
file.Read(arrayElement, 0, sizeof(int));
arr[i] = System.BitConverter.ToInt32(arrayElement);
}
file.Close();
}
}
}
You need to remember, when saving, things come out in the exact same way they go in. So since you are doing an array of 2D coordinates. That means in the loop, you would do 2 writes and 2 reads instead of one. One for each float in the coordinate.
for(int i = 0; i < arr.Length; i++)
{
byte[] arrayElement = System.BitConverter.GetBytes(arr[i].x);
file.Write(arrayElement, 0, sizeof(int));
arrayElement = System.BitConverter.GetBytes(arr[i].y);
file.Write(arrayElement, 0, sizeof(int));
}
The same principles should apply with whatever format you choose to use. You just need to find out how the co-ordinates are stored in the file so you know what datatypes to pull out the data as.
Thanks for the extensive reply. This is for binary files, but I'd like to interpret text files in a format like JSON for example. And I made a mistake, I wrote arrays, but I was thinking rather in a more flexible data collection like Dictionaries.
Your answer
Follow this Question
Related Questions
Serialized files over 4.00 GB (4294967295 bytes) cannot be loaded by the player 1 Answer
"Invalid Data File" error in every server I try (Facebook game) 1 Answer
Can't open json from editor 1 Answer
do something if a method cant be executed 1 Answer
Create a glossary using Simple JSON, loading data dynamically 1 Answer