Processing save 3D array to file and load it [duplicate] - java

This question already has answers here:
how to write an array to a file Java
(6 answers)
Closed 7 years ago.
I have a problem. I want to store a 3D array to a text file. And how could I set the array to the value of a text file?
My array:
int mosaics[][][] = new int[100][100][5];
How could I do that?
It absolutely doesn't matters how the text file looks like.
Thanks

If you just want to work with text data and not any binary then the simplest format which comes to my mind is as below
x,y,z:123
In the above format specs,
x = index of the first
y = index of the second
z = index of the third
To read this you would first
-- initialize the value of the full array to nulls or Zero
-- read the text file line by line
--- split the line on ":" , split the left side with "," comma
--- read the individual indexes and set the value for that.
To Write it will be simple as you will be writing the values through the loop.
-- to keep the file smaller, you can skip the null.

Related

Convert in reverse ascii to whole decimal in Java

Hi all and thank you for the help in advance.
I have scoured the webs and have not really turned up with anything concrete as to my initial question.
I have a program I am developing in JAVA thats primary purpose is to read a .DAT file and extract certain values from it and then calculate an output based on the extracted values which it then writes back to the file.
The file is made up of records that are all the same length and format and thus it should be fairly straightforward to access, currently I am using a loop and and an if statement to find the first occurrence of a record and then through user input determine the length of each record to then loop through each record.
HOWEVER! The first record of this file is a blank (Or so I thought). As it turns out this first record is the key to the rest of the file in that the first few chars are ascii and reference the record length and the number of records contained within the file respectively.
below are a list of the ascii values themselves as found in the files (Disregard the " " the ascii is contained within them)
"#¼ ä "
"#g â "
"ÇG # "
"lj ‰ "
"Çò È "
"=¼ "
A friend of mine who many years ago use to code in Basic recons the first 3 chars refer to the record length and the following 9 refer to the number of records.
Basically what I am needing to do is convert this initial string of ascii chars to two decimals in order to work out the length of each record and the number of records.
Any assistance will be greatly appreciated.
Edit...
Please find below the Basic code used to access the file in the past, perhaps this will help?
CLS
INPUT "Survey System Data File? : ", survey$
survey$ = "f:\apps\survey\" + survey$
reclen = 3004
OPEN survey$ + ".dat" FOR RANDOM AS 1 LEN = reclen
FIELD #1, 3 AS RL$, 9 AS n$
GET #1, 1
RL = CVI(RL$): n = CVI(n$)
PRINT "Record Length = "; RL
reclen = RL
PRINT "Number of Records = "; n
CLOSE #1
Basically what I am looking for is something similar but in java.
ASCII is a special way to translate a bit pattern in a byte to a character, and that gives each character a numerical value; for the letter 'A' is this 65.
In Java, you can get that numerical value by converting the char to an int (ok, this gives you the Unicode value, but as for the ASCII characters the Unicode value is the same as for ASCII, this does not matter).
But now you need to know how the length is calculated: do you have to add the values? Or multiply them? Or append them? Or multiply them with 128^p where p is the position, and add the result? And, in the latter case, is the first byte on position 0 or position 3?
Same for the number of records, of course.
Another possible interpretation of the data is that the bytes are BCD encoded numbers. In that case, each nibble (4bit set) represents a number from 0 to 9. In that case, you have to do some bit manipulation to extract the numbers and concatenate them, from left (highest) to right (lowest). At least you do not have to struggle with the sequence and further interpretation here …
But as BCD would require 8-bit, this would be not the right interpretation if the file really contains ASCII, as ASCII is 7-bit.

How to grab a random line from a text file and print the line [duplicate]

This question already has answers here:
How to get a random line of a text file in Java?
(7 answers)
Closed 7 years ago.
Very new to Java (only a few days into learning) I'm looking to make a random quotes program. I have the quotes on separate lines in the file quotes.txt. What I need to be able to do is grab a random line and print it.
I figure the steps are to first determine the number of lines in the file, then generate a random number between 0 and the number of lines. Then go to that line in the file and print it.
I just have no idea how to even get started really (again, forgive me, very new to Java). Any help is much appreciated.
What I would do is create an ArrayList and add the lines in there. Get a random number between 0 and (the size of the ArrayList - 1), and get the value of the information stored at that index. I will leave the code for you to try and figure out, however I will help when you post your code you have already written.
Here is a quick idea. Note I have not tested this code. Just put it together really quick... And this should be sufficient only for small files. If you need to handle larger amounts of data, then I would suggest just reading the file to the line of interest (based on random) and processing only that line. Moreover, other libs may help specifically with this problem (e.g., Apache commons: FileUtils.readLines(file).get(indexNumber))
FileInputStream fs= new FileInputStream("quotes.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
ArrayList<String> array = new ArrayList<>();
String line;
while((line = br.readLine()) != null)
array.add(line);
// variable so that it is not re-seeded every call.
Random rand = new Random();
// nextInt is exclusive. Should be good with output for array.
int randomIndex = rand.nextInt(array.size());
// Print your random quote...
System.out.println(array.get(randomIndex));
Read the file into a List or array. A Scanner or BufferedReader can accomplish this.
Use the Random class to generate a random number between 0 (inclusive) and the size of the array/List (exclusive).
Use the result from (2) to access the index of that element in the array/List from (1).

Removing file lines containing data which are not present in another file

I have a file Hier.csv which looks like this (thousands of lines):
value;nettingNodeData;ADM59505_10851487;CVAEngine;ADM;;USD;0.4;35661;BDR;NA;ICE;;RDC;MAS35661_10851487;CVAEngine;MA;10851487;RDC
I have another one, Prices.csv, which looks like this :
value;nettingNodePrices;ADM68834_22035364;CVAEngine;CVA with FTD;EUR;1468.91334249291905;DVA with FTD;EUR;5365.59742483701497
I have to make sure that both files have the same number of lines and the same ids (the third value of each lines), and it's a known fact that the set of ids from Hier.csv is larger and contains the set of ids from Prices.csv, ie. some ids that are in Hier.csv are not in Prices.csv.
Also, there are no duplicates in either file.
So far, I have tried the following, but it's taking ages, and not working (I can do it faster with my little hands and Excel, but that's not what I want).
Here is my program in pseudo code, as I don't have access to my code right now, I will edit this question as soon as I can :
for each line of Hier.csv
for each line of Prices.csv
if prices.line doesn't contain the 3rd value of hier.line
store that value in a list
end
end
end
Process p;
for each value in the list
// remove the line containing that value from Hier.csv
String[] command1 = {"sed", "'/^.*" + value + ".*$/d'", "Hier.csv", ">", "tmp.csv"};
Process p = Runtime.getRuntime().exec(command1)
end
String[] command2 = {"mv", "tmp.csv" "Hier.csv"};
Process p = Runtime.getRuntime().exec(command2)
Is there a better way than that double loop ?
Why does'nt the last part (exec(command)) work ?
And lastly, which is more efficient when reading csv files : BufferedReader or Scanner ?
You can use merge or hashtable.
Merge:
sort both files and merge together
Hashtable:
load smaller file (ids) to hashtable, loop through bigger file and test existence against hashtable

Writing/reading array to file

I have an app that will create 3 arrays : 2 with double values and one with strings that can contain anything,alphanumeric,commas,points,anything the user might want to type or type by accident. The double arrays are easy.The string one i find to be tricky.
It can contain stuff like cake red,blue 1kg paper-clip,you get the ideea.
I will need to store those arrays somehow(i guess in a file is the easiest way),read them and get them back into the app whenever the user wants to.
Also,it would be well if they wouldn't be human readable,to only be able to read them thru my app.
What's the best way to do this ? My issue is,how can i read them back into arrays.Its easy to write to a file but then to get them back in the same array i put them in...How can i separate array elements for it not to split one element in two because it has a space or any other element.
Can i like,make 3 rows of text,each element split by a tab \t or something and when i read it each element will by split by that tab ? Will this be able to create any issues when reading ?
I guess i want to know how can i split the elements of the array so that it won't be able to ever read them wrong.
Thanks and have a nice day !
If you don't want the file to be human readable, you could usejava.io.RandomAccessFile.
You would probably want to specify a maximum string size if you did this.
To save a string:
String str = "hello";
RandomAccessFile file = new RandomAccessFile(new File("filename"));
final int MAX_STRING_BYTES = 100; // max number of bytes the string could use in the file
file.writeUTF(str);
file.skipBytes(MAX_STRING_BYTES - str.getBytes().length);
// then write another..
To read a string:
// instantiate again
final int STRING_POSITION = 100; // or whichever place you saved it
file.seek(STRING_POSITION);
String str = new String(file.read(MAX_STRING_BYTES));
You would probably want a use the beginning of the file to store the size of each array. Then just store all the values one by one in the file, no need for separators.

Displaying comma-separated data stored in a .txt file

I am currently building an app which will be used to time a race.
All the times are saved in a .txt file in this format.
STARTOFEVENT,20/11/2011 11:04:58
0,20/11/2011 11:05:14
1,20/11/2011 11:05:17,00:00:02
2,20/11/2011 11:05:19,00:00:04
3,20/11/2011 11:05:20,00:00:05
4,20/11/2011 11:05:21,00:00:06
5,20/11/2011 11:05:22,00:00:07
What I need help with is displaying the position number (column 1) and finish time (column 3) in a textView / editText as the results come in.
I have tried to a bit of code for parsing CSV files but with no luck.
Example of split(...)...
String csvRecord = "1,20/11/2011 11:05:17,00:00:02";
String[] csvFields = csvRecord.split(",");
Each part of the string csvRecord separated by a comma is allocated to an element of the csvFields array. The number of array elements is dependent on the number of csv fields and is handled by the split(...) method which dynamically creates the array with the correct number.
From the above, csvFields[0] will be 1 with csvFields[1] as 20/11/2011 11:05:17 and csvFields[2] will be 00:00:02

Categories

Resources