I'm trying to delete the first 5 lines of a text file that match five values stored in an array. Here's what I have so far...
void write(String[] activecode) throws IOException
{
File productcodes = new File("productcodes.txt");
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(productcodes), charset));
File temp = File.createTempFile("productcodes", ".txt", productcodes.getParentFile());
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
int counter = 0;
for (String line; (line = reader.readLine()) != null && counter != activecode.length;)
{
line = line.replace(activecode[counter], "");
writer.println(line);
counter++;
}
reader.close();
writer.close();
productcodes.delete();
temp.renameTo(productcodes);
}
Also for reference, here is what the text file looks like...
BH390311ED6911-D8P8-BG7X
BH390311ED6912-GXKQ-BQ9V
BH390311ED6913-B6JF-55YG
BH390311ED6914-7B56-W37Y
BH390311ED6915-HPDW-V949
BH390311ED6916-3XX4-NDSN
BH390311ED6917-JH4M-PK6B
BH390311ED6918-WQKJ-5TKG
BH390311ED6919-TKS3-WHG3
BH390311ED6920-QTJV-9F43
BH390311ED6921-D45V-GHNG
BH390311ED6922-JH5F-4KXM
BH390311ED6923-6NQM-WSWF
BH390311ED6924-DMFD-BTN6
BH390311ED6925-7883-JG67
BH390311ED6926-3GRN-W7YT
BH390311ED6927-CBKB-47RW
The array is already saved as the first five values of the text file.
Any got any ideas on why the output is the text file with only the first three values remaining? I'm very new to Java (as you can probably tell :D)
EDIT:
The contents of the array activecode[] is:
BH390311ED6911-D8P8-BG7X
BH390311ED6912-GXKQ-BQ9V
BH390311ED6913-B6JF-55YG
BH390311ED6914-7B56-W37Y
BH390311ED6915-HPDW-V949
My desired output would be:
BH390311ED6916-3XX4-NDSN
BH390311ED6917-JH4M-PK6B
BH390311ED6918-WQKJ-5TKG
BH390311ED6919-TKS3-WHG3
BH390311ED6920-QTJV-9F43
BH390311ED6921-D45V-GHNG
BH390311ED6922-JH5F-4KXM
BH390311ED6923-6NQM-WSWF
BH390311ED6924-DMFD-BTN6
BH390311ED6925-7883-JG67
BH390311ED6926-3GRN-W7YT
BH390311ED6927-CBKB-47RW
Which is the original file minus the contents of the array.
This is the loop in your code:
for (String line; (line = reader.readLine()) != null && counter != activecode.length;)
{
line = line.replace(activecode[counter], "");
writer.println(line);
counter++;
}
Here's what it does: For counter = 0, 1, 2, 3, and 4, it reads a line from the input file. line.replace(activecode[counter],"") will look for the code from activecode in the input line. If it finds it, it removes it from the line. If the entire line equals the entire activecode[counter] element, then the line is replaced by an empty string "".
But then you write the line to the file. If your intent was to delete the lines from the file, this doesn't do that. line is now (probably) an empty string, and writer.println(line) will write an empty string to the output file. I'm not entirely sure what your needs are; it may be something like
if (!line.equals(activecode[counter]))
writer.println(line);
which will write out the line unless it equals activecode[counter], and if they're equal, it will skip the line and not write anything out. However, I'm not clear on what the exact requirements are--for instance, if the third line in the file equals activecode[0], what's supposed to happen? So I don't know whether the above is the correct solution. I think you'll need to define (at least for yourself) exactly what the program is supposed to do.
Finally, after this loop is done, your program doesn't read any more of the input. That is, it only reads the first five lines. Then it closes the input and output files. If you need to read the rest of the input file and copy it to the output file, you'll need to write another loop to do that.
Related
I have to modify a text file in java.
eg this is the file before modify
line
line
line
line
line
line
and after it should look like:
line
line
this is another
line
line
line
line
So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.
A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file.
But is there any way to read and modify a file like I want using the same class in java?
thx!
You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.
Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.
The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.
Try this:
public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
File file = new File(filename);
File temp = File.createTempFile("temp-file-name", ".tmp");
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
file.delete();
temp.renameTo(file);
}
The code is not tested, but it should work, you can improve the code with several validations and exception handling
I have to modify a text file in java.
eg this is the file before modify
line
line
line
line
line
line
and after it should look like:
line
line
this is another
line
line
line
line
So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.
A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file.
But is there any way to read and modify a file like I want using the same class in java?
thx!
You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.
Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.
The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.
Try this:
public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
File file = new File(filename);
File temp = File.createTempFile("temp-file-name", ".tmp");
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
file.delete();
temp.renameTo(file);
}
The code is not tested, but it should work, you can improve the code with several validations and exception handling
I'm wondering if it's possible to read a file by the line number, each with different values and make a condition where if that line contains a certain string or number specified. If it did it would, for example, take the content specified in that line into a variable?
So in a file line one has Age: 50, line 2 has Age: 23, line 3 has Age: 34. What I'm hoping for is that I look specifically at line 3 and take the number 34 and place it in a variable for use in my program.
If it is possible, how would you go about doing this?
I would say, it is not possible to directly address a specific line unless - perhaps you know the line sizes of your file, etc... to seek through the file. But you can use this to go through your file, line by line:
String line;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// do some cool stuff with this line.
}
br.close();
Possible duplicate: Reading a file and performing functions based on the contents of the line
You can always iterate through each line, keeping track of the line via an int or a short.
some code:
String line;
BufferedReader br = new BufferedReader(new FileReader(FILE_HERE));
int line = 0;
while ((line = br.readLine()) != null) {
line++;
if(line == 3){
//do whatever you want
}
}
br.close();
I will add that getting something from one single line while others also have identical info is bad
you can use the scanner object to read through a file. you would use the delimiter to find the info you want and a counter to keep track of the line, then put it in an arraylist or something. depending on what you want to do.
Scanner in = new Scanner(filename);
int line = 0;
in.useDelimiter("[regex of the info you are looking for]");
while in.hasNext()) {
line++
//do something
}
I'm writing this code to look inside a txt file and find me a string that the user gave as input. My txt file contains the lines as such (this info will be important later):
first line - blank.
second line - idan
third line - yosi
now, if the user inputs "idan" as the user (without the "") the code will find it. If the user puts in "yosi" it wont find it. It's like my code is reading only the second line. I'm new in programming and this is just a practice for me to learn how to read and write to files, please be patient with me.
here is the code (there is a catch and also the else statement but they where left off for length reasons):
//Search for the specific profile inside.
try{
BufferedReader br = new BufferedReader(new FileReader("d:\\profile.txt"));
System.out.println("Searching for your Profile...");
int linecount = 0;
String line;
while (br.readLine() !=null){
linecount++;
if(userName.contentEquals(br.readLine())){
System.out.println("Found, " + userName + " profile!");
break;
}
else{
}
The problem is this:
*if(userName.contentEquals(br.readLine())){*
you are reading an additional line. You will find it reads every other line with your implementation. That is line 2,4,6,etc
The problem is in the following place:
if(userName.contentEquals(br.readLine()))
You don't need to read it again because you have already read it in the while loop:
while (br.readLine() !=null)
So, you basically read line1 (do nothing with it), then read line2 (do something with it) and the process starts over.
You want to do something like
...
String line;
while((line = br.readLine()) != null) {
...
}
Every call to BufferedReader.readLine() reads the next available line from the file. Since you read one line in the while statement and read the next line for the if statement, you're only checking the even numbered lines.
I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.
For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:
FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;
int lines = 1;
while ((strLine = buffRead.readLine()) != null)
{
if(strLine.contains(newLines))
{
System.out.println("Line Found");
lines++;
}
}
System.out.println("Total Number Of Lines In File: " + lines);
This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.
Would anyone happen to know the reason why the above code does not work?
Read the javadocs for readLine.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))