Skipping certain parts of a textfile while reading in java - java

I have a text file that I am reading. It has chunks that I would want to remove. Is there a way I can say If the reader comes across a String "STATEMENT OF ACCOUNT" it skips reading the 10 lines before that Statement. This is the code I am currently using which is reading everything from the Text file.
for(int i = 0; i < filenames.length; i++){
FileInputStream fstemp = new FileInputStream("C:/Temporary/" + filenames[i]);
FileOutputStream fos = new FileOutputStream("C:/Statements/" + filenames[i]);
DataInputStream in1 = new DataInputStream(fstemp);
UniqueLineReader brtemp = new UniqueLineReader(new InputStreamReader(in1));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String strLine;
while((strLine = brtemp.readLine()) != null){
bw.write(strLine);
bw.newLine();
bw.flush();
}
}

I'm assuming you actually want to skip the 10 lines after the "STATEMENT OF ACCOUNT" line. In which case, you want something like this:
int linesToSkip = 0;
String strLine;
while((strLine = brtemp.readLine()) != null) {
if (linesToSkip > 0) {
linesToSkip--;
continue;
}
if (strLine.equals("STATEMENT OF ACCOUNT")) {
linesToSkip = 10;
continue;
}
bw.write(strLine);
bw.newLine();
bw.flush();
}
If you really want to somehow obliterate the previous ten lines, then you'd need to delay output (e.g. saving it in a cyclical buffer) until ten lines later, just in case you see "STATEMENT OF ACCOUNT" in a few lines' time.

You can do it by buffering the preceding 10 lines in a queue:
Queue<String> queue = new LinkedList<String>();
String strLine;
while ((strLine = brtemp.readLine()) != null {
queue.add(strLine);
if (strLine.equals("STATEMENT OF ACCOUNT")) {
queue.clear();
continue;
}
while (queue.size() >= 10) {
bw.write(queue.remove());
bw.newLine();
}
}
while (!queue.isEmpty()) {
bw.write(queue.remove());
bw.newLine();
}
bw.flush();

It sounds like you need to maintain a buffer of 10 lines so that when you encounter your special line, you can abandon the contents. Until you see it, you add every line to one end and only output from the other end when the buffer is full. The answers to this question recommend a Queue or CircularFifoBuffer for this type of situation.
Here's an untested code sample using a CircularFifoBuffer:
for (int i = 0; i < filenames.length; i++) {
FileInputStream fstemp = new FileInputStream("C:/Temporary/" + filenames[i]);
FileOutputStream fos = new FileOutputStream("C:/Statements/" + filenames[i]);
DataInputStream in1 = new DataInputStream(fstemp);
UniqueLineReader brtemp = new UniqueLineReader(new InputStreamReader(in1));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
Buffer ringbuf = new CircularFifoBuffer(10);
String strLine;
while ((strLine = brtemp.readLine()) != null) {
if (strLine.equals("STATEMENT OF ACCOUNT")) {
ringbuf.clear();
}
ringbuf.add(strLine);
if (ringbuf.isFull()) {
bw.write(ringbuf.remove());
bw.newLine();
bw.flush();
}
}
for (Object item : ringbuf) {
bw.write(item);
bw.newLine();
bw.flush();
}
}

Related

Editing a text File in Java and saving it as a new text file

I have a text file with 5 lines, I wish to read in those lines and be able to number them 1 - 5, and save them in a different file. The numbers begin before the start of the line. I have tried to hard code in a loop to read in the number but I keep getting errors.
public class TemplateLab5Bronze {
static final String INPUT_FILE = "testLab5Bronze.txt";
static final String OUTPUT_FILE = "outputLab5Bronze.txt";
public static void main(String[] args) {
try {
FileReader in = new FileReader(INPUT_FILE);
PrintWriter out = new PrintWriter(OUTPUT_FILE);
System.out.println("Working");
BufferedReader inFile = new BufferedReader(in);
PrintWriter outFile = new PrintWriter(out);
outFile.print("Does this print?\n");
String trial = "Tatot";
outFile.println(trial);
System.out.format("%d. This is the top line\n", (int) 1.);
System.out.format("%d. \n", (int) 2.);
System.out.format("%d. The previous one is blank.\n", (int) 3.);
System.out.format("%d. Short one\n", (int) 4.);
System.out.format("%d. This is the last one.\n", (int) 5.);
/*if(int j = 1; j < 6; j++){
outFile.print( i + trial);
}*/
String line;
do {
line = inFile.readLine();
if (line != null) {
}
} while (line != null);
inFile.close();
in.close();
outFile.close();
} catch (IOException e) {
System.out.println("Doesnt Work");
}
System.out.print("Done stuff!");
}
}
This is all the code I have so far, excluding the import statements, the commented for loop is what I was trying to use. Is there another way to do this?
One way to do it is to add to the printWriter while looping through the existing file:
FileReader fr = new FileReader("//your//path//to//lines.txt");
BufferedReader br = new BufferedReader(fr);
try (PrintWriter writer = new PrintWriter("//your//other//path//newlines.txt", "UTF-8")) {
String line;
int num = 1;
while ((line = br.readLine()) != null) {
writer.println(num + ". " + line);
num++;
}
}
Note: I didn't put in any catch statements, but you might want to catch some/all of the following: FileNotFoundException, UnsupportedEncodingException, IOException
You don't need two PrintWriters. Use only one.
PrintWriter outFile = new PrintWriter(OUTPUT_FILE);
You can simply use a counter instead of a for loop (which you have incorrectly written as if - as mentioned by #Shirkam)
String line;
int count=1;
do {
line = inFile.readLine();
if (line != null) {
outFile.println( count++ +"." + line);
}
} while (line != null);
inFile.close();
This works fine at my end.

replace a line to above line for every two lines java

I have a text file like this:
Emma,F,20355
Olivia,F,19553
Sophia,F,17327
Ava,F,16286
Isabella,F,15504
Mia,F,14820
Abigail,F,12311
Emily,F,11727
I am trying to remove words after , and also put two lines in one line for every two lines.
For example:
Emma Olivia
Sophia Ava
Isabella Mia
Abigail Emily
The program can do the first part, but I don't know how the program can do the second part. I can split the words and numbers after first ,, but I got stuck how I can can arrange lines.
Here is the code:
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String res;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
res = a[0] + "\n";
writer.write(res);
}
writer.close();
reader.close();
I think I need to create a for loop inside while loop, but I am not sure what to write to count even or odd lines.
Change to to something like this :
int count = 1;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
res = a[0] + count % 2 == 0 ? "\n" : " ";
count++;
writer.write(res);
}
try (
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))
) {
while (true) {
String line1 = reader.readLine();
if (line1 == null) {
break;
}
writer.write(line1.split(",", 2)[0]);
String line2 = reader.readLine();
if (line2 == null) {
writer.newLine();
break;
}
writer.write(" " + line2.split(",", 2)[0]);
writer.newLine();
}
}
int newLine = 1;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
if (newLine % 2 == 0)
res += a[0] + "\n";
else
res += a[0] + " ";
newLine++;
}
writer.write(res);
Try reading two lines in at the same time if there is a second line left in the reader.
Something like this:
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String[] b;
String res;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
if (reader.hasNext()) {
b = reader.readLine().split(",");
res = a[0] + " " + b[0] + "\n";
} else {
res = a[0]+"\n";
}
writer.write(res);
}
writer.close();
reader.close();
As mentioned above, read in two lines at a time. Combine them, then split based on the delimiter (comma) - Should then be easy to write out new format to a text file (Maybe pop the results in a list, then iterate over the list to write it out.
This is not a complete solution, but should be enough for you to get the idea.
// Read two lines at a time
String currentLine = reader.readLine(); //Emma,F,20355
String nextLine = reader.readLine(); //Olivia,F,19553
String combinedLine = currentLine + "," + nextLine;
// split into separate elements
String[] elements = combinedLine.split(",");
List<String> newLines = new ArrayList<>();
newLines.add(elements[0] + " " + elements[3]);
for (final String line : newLines) {
// write to file
writer.write(res);
}

How to append multiple text in text file

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".

Java how to copy part of a file

I have to read a file and depending of the content of the last lines, I have to copy most of its content into a new file. Unfortunately I didn't found a way to copy first n lines or chars of a file in java.
The only way I found, is copying the file using nio FileChannels where I can specifiy the length in bytes. However, therefore I would need to know how many bytes the stuff I read needed in the source-file.
Does anyone know a solution for one of these problems?
Try this:
Scanner scanner = new Scanner(yourFileObject); // initialise scanner
then
for (int i = 0; i < amountOfLines; i++) {
String line = scanner.nextLine(); // get line excluding \n at the end
// handle here
}
OR, for n chars, rather than lines:
Pattern charPattern = Pattern.compile(".")
// java.util.regex.Pattern with any char allowed
for (int i = 0; i < amountOfChars; i++) {
char next = scanner.next(charPattern).toCharArray()[0];
// handle here
}
This is, in my opinion, by far the best and easiest to write way to get the first n chars/lines from a file.
You should use a BufferedReader and read N lines which you will write into a fileX. Then redo this process until you've splitted your file into several files.
Here's a basic example:
BufferedReader bw = null;
try (BufferedReader br = new BufferedReader(new FileReader(new File("<path_to_input_file>")))) {
String line = "";
StringBuilder sb = new StringBuilder();
int count = 0;
bw = new BufferedWriter(new FileWriter(new File("<path_to_output_file>")));
while ( (line = br.readLine()) != null) {
sb.append(line)
.append(System.getProperty("line.separator"));
if (count++ == 1000) {
//flush and close current content into the current new file
bw.write(sb.toString());
bw.flush();
bw.close();
//start a new file
bw = new BufferedWriter(new FileWriter(new File("<path_to_new_output_file>")));
//re initialize the counter
count = 0;
//re initialize the String content
sb = new StringBuilder();
}
}
if (bw != null && sb.length() > 0) {
bw.write(sb.toString());
bw.flush();
bw.close();
}
} catch (Exception e) {
e.printStacktrace(System.out);
}
Since you have performance as key quality attribute, use BufferedReader over Scanner. Here's an explanation about the performance comparison: Scanner vs. BufferedReader

Only prints out last line to the text file and not the rest in java

I am trying to print a file to the text file. Although I have managed to make it work, it only prints out the last line that is printed on the console. E.g. My console has around 8000 lines but it only prints out the last line in the text file, and I want to print all the lines into the text file.
This is the code:
try {
BufferedReader reader = new BufferedReader(new FileReader("JDT.txt"));
Writer output = null;
File file = new File("output.txt");
output = new BufferedWriter(new FileWriter(file));
String line = reader.readLine();
int count=0;
while(line !=null)
{
for(int i = 0 ; i<faults.length;i++){
if(line.contains(faults[i]))
System.out.println(line);
count++;
output.write(line +"Total: "+count);
//System.out.println("File Written");
}
line=reader.readLine();
}
System.out.println("Printed Lines =" +count);
output.close();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Thank you in advanced.
You are re-creating and overwriting your file in each loop. Create your file and your BufferedWriter before your loops, and close it after your loops finish.
You should place these lines before the beginning of the while loop.
Writer output = null;
File file = new File("output.txt");
output = new BufferedWriter(new FileWriter(file));
And close the Writer after while loop exits.
output.close();
Also the statement output.write(line +"Total: "+count); is trying to write every line at the end of another, resulting in one big line of output. Replace it with:
output.write(line + "Total: " + count + "\n");
This should result in each line getting printed on a new line.
Not sure if it's expected but in your code output.write might get executed multiple times for the same line depending on the length of your faults variable. This will result in same line getting printed more than once.
If the length of the faults is n the write will be called n times for the same line.
I think you need this:
while (line != null) {
for (int i = 0; i < faults.length; i++) {
if (line.contains(faults[i])) {
count++;
output.write(line + "Total: " + count + "\n");
System.out.println(line);
break;
}
}
// System.out.println("File Written");
line = reader.readLine();
}
I thought I'd put this here for reference. It's just a general approach for copying lines from an input file to an output file.
final class Sample
{
private static final String inputFile = "input_file.txt";
private static final String outputFile = "output_file.txt";
public void start()
{
BufferedReader bufferedReader;
BufferedWriter bufferedWriter;
try
{
bufferedReader = new BufferedReader(new FileReader(inputFile));
bufferedWriter = new BufferedWriter(new FileWriter(outputFile));
copyContents(bufferedReader, bufferedWriter);
bufferedReader.close();
bufferedWriter.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
private void copyContents(final BufferedReader bufferedReader, final BufferedWriter bufferedWriter)
{
try
{
String line = bufferedReader.readLine();
while (null != line)
{
bufferedWriter.write(line + '\n');
line = bufferedReader.readLine();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Categories

Resources