-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileSplit.java
95 lines (85 loc) · 2.7 KB
/
FileSplit.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class FileSplit
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter count of parts:");
int count = sc.nextInt();
System.out.println("Enter source file name:");
String fileFullName= sc.next();
String fileName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
File f=new File(fileFullName);
try(FileReader reader = new FileReader(f))
{
char[] buffer = new char[(int)f.length()];
// считаем файл полностью
reader.read(buffer);
String[] inStrAr = new String(buffer).split("\r\n");
String header = inStrAr[0];
int countLines = inStrAr.length / count + 1;
int i = 0;
int fileNum = 1;
String text = "";
for (String str : inStrAr) {
if (i < countLines) {
text += str + "\r\n";
i++;
} else {
text += str + "\r\n";
if (fileNum != 1) {
text = header + "\r\n" + text;
}
File newFile = new File(fileName+"_parts\\"+fileName+"_" + fileNum + ".txt");
File directory = new File(newFile.getParentFile().getAbsolutePath());
if (!directory.exists()) directory.mkdirs();
if (newFile.createNewFile()) {
System.out.println("New file "+fileName+"_" + fileNum + ".txt created.");
} else {
System.out.println("File "+fileName+"_" + fileNum + ".txt exists.");
}
try(FileWriter writer = new FileWriter(newFile, false))
{
// запись всей строки
writer.write(text);
writer.flush();
text = "";
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
fileNum++;
i = 0;
}
}
if (text != ""){
if (fileNum != 1) {
text = header + "\r\n" + text;
}
File newFile = new File(fileName+"_parts\\"+fileName+"_" + fileNum + ".txt");
if (newFile.createNewFile()) {
System.out.println("New file "+fileName+"_" + fileNum + ".txt created.");
} else {
System.out.println("File "+fileName+"_" + fileNum + ".txt exists.");
}
try(FileWriter writer = new FileWriter(newFile, false))
{
// запись всей строки
writer.write(text);
writer.flush();
text = "";
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}