-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertByteArrayToFile.java
64 lines (52 loc) · 1.48 KB
/
ConvertByteArrayToFile.java
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
package com.javamultiplex.filehandling;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class ConvertByteArrayToFile {
public static void main(String[] args) throws IOException {
Scanner input = null;
FileOutputStream fos = null;
try {
input = new Scanner(System.in);
System.out.println("Enter file name with extension : ");
String fileName = input.nextLine();
System.out.println("Enter length of byte array : ");
int length=input.nextInt();
if (isValidFileName(fileName)) {
File file = new File(fileName);
if (file.exists()) {
byte[] byteArray = new byte[length];
System.out.println("Enter " length " bytes (ASCII value) : ");
for(int i=0;i<length;i )
{
byteArray[i]=input.nextByte();
}
fos=new FileOutputStream(file);
//Writing byte[] to file.
fos.write(byteArray);
System.out.println("Data has been written successfully.");
} else {
System.out.println("File not exists in current directory.");
}
} else {
System.out.println("File name is invalid.");
}
} finally {
if (input != null) {
input.close();
}
if (fos != null) {
fos.close();
}
}
}
private static boolean isValidFileName(String fileName) {
String pattern = "^. \\.. $";
boolean result = false;
if (fileName.matches(pattern)) {
result = true;
}
return result;
}
}