My simple program takes input from keyboard or text field and put it to JTextArea like this:
1111,1111;\n
2222,2222;\n
3333,3333;\n
.
.
.
\n
When I finish inputting data i want to save it to the txt file, but there is one condition - when there are more then 30 lines, data from jtextarea have to be split into smaller "packages" (every one have to have only 30 lines (or the last one less) and they have to be saved to separated txt files. Every file have to have empty line at the end (\n).
I know how to create files.
I can count into how many pieces i have to split data from jtextarea.
But i can't figure it out how to read 1-30 lines by scaner in the first run and save it to file, 31-60 in the second run and save etc etc.
String string = jtextarea.getText() gets all the lines
I try also something like this:
for (int i=1; i<31; i++)
{
while(scaner.hasNext())
pw.println(scaner.nextLine());
}
but it also reads all the lines
This also not working - gives only 30 characters - not lines:
String alltext = jtextare.getText();
String lines = alltext.substring(0, 30);
This example i don't understand:
String text = inputArea.getText();
int totalLines = inputArea.getLineCount();
for (int i=0; i < totalLines; i++) {
int start = inputArea.getLineStartOffset(i);
int end = inputArea.getLineEndOffset(i);
String line = text.substring(start, end);
outputArea.append(line + "\n");
}
Why bother when i can't point line number, only position in line.
Please help me with this problem - can you describe proper loop and commands for this?
SIMPLE DESCRIPTION OF PROBLEM
I have jTextArea with 100 lines of text. Every line ending with \n.
I want to split this 100 lines into groups of 30 lines per group, and write every group to txt file - every txt file will contain 30 lines of text (every line ending with \n), and last (31) line should be empty. What is the easiest way to do this?
This works:
try
{
Scanner sc = new Scanner(ta.getText());
String s="";
for(int i=1; i<=100; i++)
{
s+=sc.nextLine()+"\r\n";
if(i%30==0)
{
File f = new File("File"+(i/30)+".txt");
f.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(s);
bw.close();
s="";
}
}
File f = new File("File4.txt");
f.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(s);
bw.close();
}catch(Exception e){}