-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathByteArraySpeichern
88 lines (80 loc) · 2.66 KB
/
ByteArraySpeichern
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteArraySpeichern {
public static int[] ZufallsListe(int n){
int[] liste = new int[n];
int x;
for(int i=0; i<n;i++){
x = (int) Math.floor(n*Math.random()+1);
liste[i] = x;
}
return liste;
}
public static String convertToString(int[] liste) {
int c;
char m;
StringBuilder ans = new StringBuilder();
for(int i = 0;i<liste.length;i++){
while (liste[i] > 0) {
c = liste[i] % 10;
liste[i] = liste[i] / 10;
m = (char) ('0' + c);
ans.append(m);
}
ans.append("|");
}
return ans.reverse().toString();
}
private boolean writeData(byte[] data, String fileName) {
File file = new File(fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
return true;
} catch (FileNotFoundException e) {
System.err.println(file + " doesn't exist!");
} catch (IOException e) {
System.err.println("Problems writing data to " + file);
} finally {
try {
if(fos != null) fos.close();
}catch(IOException e){}
}
return false;
}
private byte[] readData(String fileName) {
File file = new File(fileName);
FileInputStream fis = null;
byte[] data = null;
try {
fis = new FileInputStream(file);
data = new byte[(int) file.length()];
fis.read(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fis != null) fis.close();
} catch (IOException e) {}
}
return data;
}
public static void main(String[] args) {
int[] liste = ZufallsListe(25);
String Array = convertToString(liste);
String fileName = "test";
ByteArraySpeichern bas = new ByteArraySpeichern();
if (bas.writeData(new String(Array).getBytes(), fileName))
System.out.println("'" + Array
+ "' erfolgreich als byte[] gespeichert");
String ergebnis = new String(bas.readData(fileName));
System.out.println("Aus Datei gelesen: '" + ergebnis + "'");
}
}