Unable to write to a file till some specific line - java

I am trying to split files from one file to 4 different files. So I am dividing the file by some "x" value and wanna write the file till that value and from there to next file continues till the file contents ends.
I am checking some x value in the file using buffer reader and checking with the content is equal to the x value and do the splitting.
Splitting is coming but in some another way, like it's reading the file and writing till the line number which is "x". But I need all the lines till that "x" value is present in the file.
I have a time in the file like start time hh:mm:ss and I am checking this with the hh:mm:ss with my x value and do the splitting like below
// inputs to the below method
// filePath = "//somepath";
// splitlen = 30;
// name ="somename"; */
public void split(String FilePath, long splitlen, String name) {
long leninfile = 0, leng = 0;
int count = 1, data;
try {
File filename = new File(FilePath);
InputStream infile = new BufferedInputStream(new FileInputStream(filename));
data = infile.read();
BufferedReader br = new BufferedReader(new InputStreamReader(infile));
while (data != -1) {
filename = new File("/Users//Documents/mysrt/" + count + ".srt");
OutputStream outfile = new BufferedOutputStream(new FileOutputStream(filename));
String strLine = br.readLine();
String[] atoms = strLine.split(" --> ");
if (atoms.length == 1) {
// outfile.write(Integer.parseInt(strLine + "\n"));
}
else {
String startTS = atoms[0];
String endTS = atoms[1];
System.out.println(startTS + "\n");
System.out.println(endTS + "\n");
String startTime = startTS.replace(",", ".");
String endTime = endTS.replace(",", ".");
System.out.println("startTime" + "\n" + startTime);
System.out.println("endTime" + "\n" + endTime);
String [] arrOfStr = endTime.split(":");
System.out.println("=====arrOfStr=====");
int x = Integer.parseInt(arrOfStr[1]);
System.out.println(arrOfStr[1]);
System.out.println("===x repeat==");
System.out.println(x);
System.out.println("===splitlen repeat==");
System.out.println(splitlen);
System.out.println(data);
System.out.println(br.readLine());
System.out.println(br.read());
while (data != -1 && x < splitlen) {
outfile.write(br.readLine().getBytes());
data = infile.read();
x++;
}
System.out.println("===== out of while x =====");
System.out.println(br.readLine());
System.out.println(x);
leninfile += leng;
leng = 0;
outfile.close();
firstPage = false;
firstPage = true;
count++;
splitlen = splitlen + 30;
System.out.println("=====splitlen after=====" +splitlen);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am incrementing the time with some number to read the next lines in file and with into another file.
Here splitlen is 30 , so it's writing the data till 30 lines in a new file. Then it's incrementing splitlen+30 i.e 60. But, it's reading next 60 lines and writing into next file.
But I need to check this splitlen with the time provided in the content of file and I should split that line.
Please suggest me where I am doing wrong. If you provide snippet it will be appreciated.
Thanks.

I think this is what you want
public void split(String filePath, long splitLen, String name) {
File fileSource = new File(filePath);
int count = 0;
boolean endOfFile = false;
String lineSeparator = System.getProperty("line.separator");
int hour = 0; // an accumulator for hours
int min = 0; // an accumulator for minutes
int sec = (int) splitLen; // an accumulator for seconds
int _hour = 0; // hours from the file
int _min = 0; // minutes from the file
int _sec = 0; // seconds from the file
try ( // try with resources to close files automatically
FileReader frSource = new FileReader(fileSource);
BufferedReader buffSource = new BufferedReader(frSource);
) {
String strIn = null;
while(!endOfFile) {
File fileOut = new File("f:\\test\\mysrt\\" + count + ".srt");
try ( // try with resources to close files automatically
FileWriter fwOut = new FileWriter(fileOut);
) {
if (strIn != null) {
// write out the last line read to the new file
fwOut.write(strIn + lineSeparator);
}
for (int i = 0; i < splitLen; i++) {
strIn = buffSource.readLine();
if (strIn == null) {
endOfFile = true; // stop the while loop
break; // exit the for loop
}
if (strIn.indexOf("-->") > 0) {
String endTime = strIn.split("-->")[1];
_hour = extractHours(endTime); // get the hours from the file
_min = extractMinutes(endTime); // get the minutes from the file
_sec = extractSeconds(endTime); // get the seconds from the file
if (_hour >= hour && _min >= min && _sec >= sec) { // if the file time is greater than our accumulators
sec += splitLen; // increment our accumulator seconds
if (sec >= 60) { // if accumulator seconds is greater than 59, we need to convert it to minutes and seconds
min += sec / 60;
sec = sec % 60;
}
if (min >= 60) { if accumulator minutes is greater than 59, we need to convert it to hours and minutes
hour += min / 60;
min = min % 60;
}
break; // break out of the for loop, which cause the file to be completed and a new file started.
}
}
fwOut.write(strIn + lineSeparator); // write out to the new file
}
fwOut.flush();
}
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private int extractMinutes(String time) {
// You need to implement this, I don't know the format of your time
return 0;
}
private int extractSeconds(String time) {
// You need to implement this, I don't know the format of your time
return 0;
}

The problem with your code is that the timestamp you're looking at is in HH:MM:ss but with the splitlen and x variables you are only working with minutes.
So you need to keep track of both hours and minutes, maybe this could be done with some DateTime class but here is a simple int solution
//somewhere at the top
int hour = 0;
int minutes = 30;
//where you today increase splitlen
minutes += 30;
if (minutes == 60) {
hour++;
minutes = 0;
}
//parse also hours
int y = Integer.parseInt(arrOfStr[0]);
int x = Integer.parseInt(arrOfStr[1]);
//you need to rewrite this to compare x and y against hour and minutes
while (data != -1 && x < splitlen) {
So now you will not be looking for 30, 60, 90,... minutes but instead 00:30, 01:00, 01:30 and so on. Of course you must also be prepared to handle the situation where there is no entry for a whole minute unless of course you already do so.
checkTime is of course a a key method here and it might be a good idea to make the last hour and minute when the file was split into class members but they could of course also be sent as parameters from split().
Update
Here is a simplified version of the split method to give an example on how to solve this, it is not complete but should be a good starting point for solving the issue. I try to make use of how a .str file is constructed and make use of the logic explained above for determining when to open a new output file.
public void split(String filepath, long splitlen, String name) {
int count = 1;
try {
File filename = new File(filepath);
InputStream infile = new BufferedInputStream(new FileInputStream(filename));
BufferedReader br = new BufferedReader(new InputStreamReader(infile));
FileWriter outfile = createOutputFile(count);
boolean isEndOfFile = false;
while (!isEndOfFile) {
String line = null;
int i = 1;
while ((line = br.readLine()) != null) {
outfile.write(line);
if (line.trim().isEmpty()) { //last line of group
i = 1;
continue;
}
if (i == 2) { //Timestamp row
String[] split = line.split("-->");
if (checkTime(split)) {
count++;
outfile.flush();
outfile.close();
outfile = createOutputFile(count);
}
}
i++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private FileWriter createOutputFile(int index) {
//Create new outputfile and writer
return null;
}
private boolean checkTime(String[] arr) {
//use start or end time in arr to check if an even half or full hour has been passed
return true;
}

Related

Retrieve number of lines in file from JFileChooser Java

Is there a way in Java to know the number of lines of a file chosen?
The method chooser.getSelectedFile().length() is the only method I've seen so far but I can't find out how to find the number of lines in a file (or even the number of characters)
Any help is appreciated, thank you.
--update--
long totLength = fc.getSelectedFile().length(); // total bytes = 284
double percentuale = 100.0 / totLength; // 0.352112676056338
int read = 0;
String line = br.readLine();
read += line.length();
Object[] s = new Object[4];
while ((line = br.readLine()) != null)
{
s[0] = line;
read += line.length();
line = br.readLine();
s[1] = line;
read += line.length();
line = br.readLine();
s[2] = line;
read += line.length();
line = br.readLine();
s[3] = line;
read += line.length();
}
this is what I tried, but the number of the variable read at the end is < of the totLength and I don't know what File.length() returns in bytes other than the content of the file.. As you can see, here i'm trying to read characters though.
Down and dirty:
long count = Files.lines(Paths.get(chooser.getSelectedFile())).count();
You may find this little method handy. It gives you the option to ignore counting blank lines in a file:
public long fileLinesCount(final String filePath, boolean... ignoreBlankLines) {
boolean ignoreBlanks = false;
long count = 0;
if (ignoreBlankLines.length > 0) {
ignoreBlanks = ignoreBlankLines[0];
}
try {
if (ignoreBlanks) {
count = Files.lines(Paths.get(filePath)).filter(line -> line.length() > 0).count();
}
else {
count = Files.lines(Paths.get(filePath)).count();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return count;
}
You could use the JFileChooser to select a file, than open the file using a file reader and as you iterate over the file just increment a counter, like this...
while (file.hasNextLine()) {
count++;
file.nextLine();
}

Java BufferedReader readline calculate values from file

I am new to Java and at the moment lost.
I have this code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
/**
*
* #author Darwish
*/
public class M3UReader {
/**
* #param args the command line arguments
*/
public static boolean isValidHeader(String playList)
{
boolean returnValue = false;
BufferedReader br;
try
{
br = new BufferedReader(new FileReader(new File(playList)));
String s = br.readLine(); // declares the variable "s"
if(s.startsWith("#EXTM3U")) { // checks the line for this keyword
returnValue = true; // if its found, return true
}
br.close();
}
catch (Exception e)
{
System.err.println("isValidHeader:: error with file "+ playList + ": " + e.getMessage());
}
return returnValue;
}
public static int getNumberOfTracks(String playList)
{
int numberOfTracks = 0; // sets the default value to zero "0"
try
{
BufferedReader br = new BufferedReader(new FileReader(new File(playList)));
String s;
while((s = br.readLine())!=null) // if "s" first line is not null
{
if(s.startsWith("#")==false) { // if the first line starts with "#" equals to false.
numberOfTracks++; // increments
}
}
br.close();
}
catch (Exception e)
{
numberOfTracks = -1; // chek if the file doesnt exist
System.err.println("could not open/read line from/close filename "+ playList);
}
return numberOfTracks;
}
public static int getTotalMinutes(String playList)
{
// code needed here
}
public static void main(String[] args) {
// TODO code application logic here
String filename = "files\\playlist.m3u"; // finds the file to read (filename <- variable declaration.)
boolean isHeaderValid = M3UReader.isValidHeader(filename); // declares the variabe isHeaderValid and links it with the class isValidHeader
System.out.println(filename + "header tested as "+ isHeaderValid); // outputs the results
if(isHeaderValid)
{
int numOfTracks = M3UReader.getNumberOfTracks(filename);
System.out.println(filename + " has "+ numOfTracks + " tracks ");
}
}
}
On the method getTotalMinutes, I have to find a way to calculate the totals of the int values that was read from the file. The File has this data:
#EXTM3U
#EXTINF:537,Banco De Gaia - Drippy F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\01 Drippy.mp3
#EXTINF:757,Banco De Gaia - Celestine F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\02 Celestine.mp3
#EXTINF:565,Banco De Gaia - Drunk As A Monk F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\03 Drunk As A Monk.mp3
#EXTINF:369,Banco De Gaia - Big Men Cry F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\04 Big Men Cry.mp3
The number after the #EXTINF: is the length of the music which from the data above is in seconds.
I don't know what code to write on the getTotalMinutes method to get the program to read the minutes from the file and then calculate all of them to get the total of minutes. I searched the web on how to do this unfortunately I can't find any. So any help is appreciated.
You can use this, its just copy of your getNumberTracks method but it is parsing the file the way you need to get total minutes :
public static final String beginning = "#EXTINF:";
public static final String afterNumber = ",";
public static int getTotalMinutes(String playList) {
int value = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(new File(playList)));
String s;
while ((s = br.readLine()) != null) // if "s" first line is not null
{
if (s.contains(beginning)) {
String numberInString = s.substring(beginning.length(), s.indexOf(afterNumber));
value += Integer.valueOf(numberInString);
}
}
br.close();
} catch (Exception e) {
}
return value;
}
So, based on the description provided from here, the numeric value is the number of seconds.
So, given a String in the format of #EXTINF:{d},{t} you should be able to use simple String manipulation to get the value out...
String text = "#EXTINF:537,Banco De Gaia - Drippy F:\\SortedMusic\\Electronic\\Banco De Gaia\\Big Men Cry\\01 Drippy.mp3";
String durationText = text.substring(text.indexOf(":") + 1, text.indexOf(","));
int durationSeconds = Integer.parseInt(durationText);
System.out.println(durationSeconds);
Which will print 537...
Next we just need to do some simple time arithmetic...
double seconds = durationSeconds;
int hours = (int)(seconds / (60 * 60));
seconds = seconds % (60 * 60);
int minutes = (int)(seconds / 60);
seconds = seconds % (60);
System.out.println(hours + ":" + minutes + ":" + NumberFormat.getNumberInstance().format(seconds));
Which prints 0:8:57 (or 8 minutes and 57 seconds)
To read M3U files you'll want to search for information about M3U parsers. There are already many efficient open source parsers available, but you will need to pay close attention to their licenses if you are planning on selling or distributing this.
M3u Parser looks like promising if you just want something quick and efficient.
M3u Parser
public static int getTotalMinutes(String filename) {
int totalSeconds = 0;
if (isValidHeader(filename)) {
try (BufferedReader br = new BufferedReader(new FileReader(new File(filename)));) {
String nextLine;
while ((nextLine = br.readLine()) != null) {
//If the next line is metadata it should be possible to extract the length of the song
if (nextLine.startsWith(M3U_METADATA)) {
int i1 = nextLine.indexOf(":");
int i2 = nextLine.indexOf(",");
String substr = nextLine.substring(i1 + 1, i2);
totalSeconds += Integer.parseInt(substr);
}
}
} catch (IOException | NumberFormatException e) {
//Exception caught - set totalSeconds to 0
System.err.println("getTotalSeconds:: error with file " + filename + ": " + e.getMessage());
totalSeconds = 0;
}
}
return totalSeconds;
}

Find file with the most update information

I have a list of log files, and I need to find which one has a latest edition of a specific line, and all or none could have this line.
The lines in the files look like this:
2013/01/06 16:01:00:283 INFO ag.doLog: xxxx xxxx xxxx xxxx
And I need a line lets say
xx/xx/xx xx:xx:xx:xxx INFO ag.doLog: the line i need
I know how to get an array of files, and if I scan backwards I could find the latest latest line in each file (if it exists).
Biggest problem is that the file could be big (2k lines?) and I want to find the line in a relative fast way (a few seconds), so I am open for suggestion.
Personal ideas:
If a file has the line at X time, then any file that has not found the line before X time should not be scan anymore. This will require to search all files at the same time, which i dont know how.
Atm the code breaks, and I suppose if lack of memory.
Code:
if(files.length>0) { //in case no log files exist
System.out.println("files.length: " + files.length);
for(int i = 0; i < files.length; i++) { ///for each log file look for string
System.out.println("Reading file: " + i + " " + files[i].getName());
RandomAccessFile raf = new RandomAccessFile(files[i].getAbsoluteFile(), "r"); //open log file
long lastSegment = raf.length(); //Finds how long is the files
lastSegment = raf.length()-5; //Sets a point to start looking
String leido = "";
byte array[] = new byte[1024];
/*
* Going back until we find line or file is empty.
*/
while(!leido.contains(lineToSearch)||lastSegment>0) {
System.out.println("leido: " + leido);
raf.seek(lastSegment); //move the to that point
raf.read(array); //Reads 1024 bytes and saves in array
leido = new String(array); //Saves what is read as a string
lastSegment = lastSegment-15; //move the point a little further back
}
if(lastSegment<0) {
raf.seek(leido.indexOf(lineToSearch) - 23); //to make sure we get the date (23 characters long) NOTE: it wont be negative.
raf.read(array); //Reads 1024 bytes and saves in array
leido = new String(array); //make the array into a string
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(leido.substring(0, leido.indexOf(" INFO "))); //get only the date part
System.out.println(date);
//if date is bigger than the other save file name
}
}
}
I find the code difficult to verify. One could split the task in a backwards reader, which reads lines from file end to start. And use that for parsing dates line wise.
Mind, I am not going for nice code, but something like this:
public class BackwardsReader implements Closeable {
private static final int BUFFER_SIZE = 4096;
private String charset;
private RandomAccessFile raf;
private long position;
private int readIndex;
private byte[] buffer = new byte[BUFFER_SIZE];
/**
* #param file a text file.
* #param charset with bytes '\r' and '\n' (no wide chars).
*/
public BackwardsReader(File file, String charset) throws IOException {
this.charset = charset;
raf = new RandomAccessFile(file, "r");
position = raf.length();
}
public String readLine() throws IOException {
if (position + readIndex == 0) {
raf.close();
raf = null;
return null;
}
String line = "";
for (;;) { // Loop adding blocks without newline '\n'.
// Search line start:
boolean lineStartFound = false;
int lineStartIndex = readIndex;
while (lineStartIndex > 0) {
if (buffer[lineStartIndex - 1] == (byte)'\n') {
lineStartFound = true;
break;
}
--lineStartIndex;
}
String line2;
try {
line2 = new String(buffer, lineStartIndex, readIndex - lineStartIndex,
charset).replaceFirst("\r?\n?", "");
readIndex = lineStartIndex;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(BackwardsReader.class.getName())
.log(Level.SEVERE, null, ex);
return null;
}
line = line2 + line;
if (lineStartFound) {
--readIndex;
break;
}
// Read a prior block:
int toRead = BUFFER_SIZE;
if (position - toRead < 0) {
toRead = (int) position;
}
if (toRead == 0) {
break;
}
position -= toRead;
raf.seek(position);
raf.readFully(buffer, 0, toRead);
readIndex = toRead;
if (buffer[readIndex - 1] == (byte)'\r') {
--readIndex;
}
}
return line;
}
#Override
public void close() throws IOException {
if (raf != null) {
raf.close();
}
}
}
And a usage example:
public static void main(String[] args) {
try {
File file = new File(args[0]);
BackwardsReader reader = new BackwardsReader(file, "UTF-8");
int lineCount = 0;
for (;;) {
String line = reader.readLine();
if (line == null) {
break;
}
++lineCount;
System.out.println(line);
}
reader.close();
System.out.println("Lines: " + lineCount);
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}

union of two files with array

I am beginner of Java.
I am trying to read two files and then get the union of them. I should use an array with size 100. (only one array allowed)
First, I read all records from file1, and write them to the output, file3. For that purpose, I read 100 records at a time, and write them to file3 using iteration.
After that, like file1, this time I read second file as 100 records at a time, and write them to the array, memory[]. Then I find the common records, if the record which I read from file2 is not in file1, I write it to the output file. I do this until reader2.readLine() gets null and I re-open file1 in each iteration.
This is what I have done so far, almost done, but it gives NullPointerException. Any help would be appreciated.
Edit: ok, now it doesn't give any exception, but it doesn't find the different records and can't write them. I guess the last for loop and booleans don't work , why? please help...
import java.io.*;
public class FileUnion
{
private static long startTime, endTime;
public static void main(String[] args) throws IOException
{
System.out.println("PROCESSING...");
reset();
startTimer();
String[] memory = new String[100];
int memorySize = memory.length;
File file1 = new File("stdlist1.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
File file3 = new File("union.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file3));
int numberOfLinesFile1 = 0;
String line1 = null;
String line11 = null;
while((line1 = reader1.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line1;
i++;
if(i < memorySize)
{
line1 = reader1.readLine();
}
}
for (int i = 0; i < memorySize; i++)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
reader1.close();
File file2 = new File("stdlist2.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line2 = null;
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
line2 = reader2.readLine();
}
}
for (int k = 0; k < memorySize; k++ )
{
boolean found = false;
File f1 = new File("stdlist1.txt");
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for (int m = 0; m < numberOfLinesFile1; m++)
{
line11 = buff1.readLine();
if (line11.equals(memory[k]) && found == false);
{
found = true;
}
}
buff1.close();
if (found == false)
{
writer.write(memory[k]);
writer.newLine();
}
}
}
reader2.close();
writer.close();
endTimer();
long time = duration();
System.out.println("PROCESS COMPLETED SUCCESSFULLY");
System.out.println("Duration: " + time + " ms");
}
public static void startTimer()
{
startTime = System.currentTimeMillis();
}
public static void endTimer()
{
endTime = System.currentTimeMillis();
}
public static long duration()
{
return endTime - startTime;
}
public static void reset()
{
startTime = 0;
endTime = 0;
}
}
memory[k] is null. Why is this null? Because in this code:
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < 100; i++)
{
memory[i] = line1;
i++;
if(i < 100)
{
line2 = reader2.readLine();
}
}
you say memory[i] = line1;
line1 however is always null because you used it before in a loop which ended when line1 is null.
I believe you intended to write **memory[i] = line2;** in the above code :)
You have to check that you've not yet reached the end of the file. In all loops where you have a lineX = readerX.readLine(), immediately check whether lineX == null and break out of the loop if it is.
Edit my own answer because code doesn't show well in comments.
while(!line11.equals(memory[k]))
{
line11 = buff1.readLine();
}
It's line11 that is (sometimes) null here. If memory[k] is not in file1, what happens?

reading from the file and writing to the file in java

I am beginner with Java.
This is my approach:
I am trying to read two files and then get the union of them. I should am using an array with size 100. (just one array allowed, reading and writing line by line or arrayList or other structures are not allowed.)
First, I read all records from file1, and write them to the output, a third file. For that purpose, I read 100 record at a time, and write them to the third file using iteration.
After that, like first file, this time I read second file as 100 records at a time, and write them to the memory[]. Then I find the common records, if the record which I read from File2 is not in File1, I write it to the output file. I do this until reader2.readLine() gets null and I re-open file1 in each iteration.
This is what I have done so far, almost done. Any help would be appreciated.
Edit: ok, now it doesn't give any exception, but it can't find the different records and can't write them. I guess the last for loop and booleans don't work , why? I really need help. Thanks for your patience.
import java.io.*;
public class FileUnion
{
private static long startTime, endTime;
public static void main(String[] args) throws IOException
{
System.out.println("PROCESSING...");
reset();
startTimer();
String[] memory = new String[100];
int memorySize = memory.length;
File file1 = new File("stdlist1.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
File file3 = new File("union.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file3));
int numberOfLinesFile1 = 0;
String line1 = null;
String line11 = null;
while((line1 = reader1.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line1;
i++;
if(i < memorySize)
{
line1 = reader1.readLine();
}
}
for (int i = 0; i < memorySize; i++)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
reader1.close();
File file2 = new File("stdlist2.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line2 = null;
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
line2 = reader2.readLine();
}
}
for (int k = 0; k < memorySize; k++ )
{
boolean found = false;
File f1 = new File("stdlist1.txt");
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for (int m = 0; m < numberOfLinesFile1; m++)
{
line11 = buff1.readLine();
if (line11.equals(memory[k]) && found == false);
{
found = true;
}
}
buff1.close();
if (found == false)
{
writer.write(memory[k]);
writer.newLine();
}
}
}
reader2.close();
writer.close();
endTimer();
long time = duration();
System.out.println("PROCESS COMPLETED SUCCESSFULLY");
System.out.println("Duration: " + time + " ms");
}
public static void startTimer()
{
startTime = System.currentTimeMillis();
}
public static void endTimer()
{
endTime = System.currentTimeMillis();
}
public static long duration()
{
return endTime - startTime;
}
public static void reset()
{
startTime = 0;
endTime = 0;
}
}
EDIT! Redo.
Ok, so to use 100 lines at a time you need to check for null, otherwise trying to write null to a file could cause errors.
You are checking if the file is at the end once, and then gathering 99 more peices of info without checking for null.
What if when this line is called:
while((line2 = reader2.readLine()) != null)
there is only 1 line left in the file? Then your memory array contains 99 instances of null, and you try to write null to the file 99 times. That's worse case scenario.
I don't really know how much help we are supposed to give to people looking for homework help, on most sites I'm familiar with it's not even allowed.
here is an example of one way to write the first file.
String line1 = reader1.readLine();
boolean end_of_file1 = false;
while(!end_of_file)
{
for (int i = 0; i < memorySize)
{
memory[i] = line1;
i++;
if(i < memorySize)
{
if((line1 = reader1.readLine()) == null)
{
end_of_file1 = true;
}
}
}
for (int i = 0; i < memorySize; i++)
{
if(!memory[i] == null)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
}
reader1.close();
once you have that, to make the checking for copies easier, make a public static boolean that checks the file for it, then you can call that, it will make the code cleaner.
public static boolean isUsed(String f1, String item, int dist)
{
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for(int i = 0;i<dist;i++)
{
String line = buff1.readLine()
if(line == null){
return false;
}
if(line.equals(item))
{
return true;
}
}
return false;
}
Then use the same method as writing file 1, only before writing each line check to see if !isUsed()
boolean end_of_file2 = false;
memory = new String[memorySize];// Reset the memory, erase old data from file1
int numberOfLinesFile2=0;
String line2 = reader2.readLine();
while(!end_of_file2)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
if((line2 = reader2.readLine()) == null)
{
end_of_file2 = true;
}
}
}
for (int i = 0; i < memorySize; i++)
{
if(!memory[i] == null)
{
//Check is current item was used in file 1.
if(!isUsed(file1, memory[i], numberOfLinesFile1)){//If not used already
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile2++;
}
}
}
}
reader2.close();
writer.close();
Hope this helps. Notice I'm not supplying the full code, because I've learned that just pasting the code will make it more likely for copy and paste to just use a code without understanding it. I hope you find it useful.

Categories

Resources