Overwriting data in a file starting from a given line in java - java

I want to specifically overwrite data in a file starting from a given line.
Suppose that I find out that I have to write some data in the file from line x ( I have already found x) . How would I overwrite everything after there.
Also is there a function that would directly take my line and string and overwrite the file.

An alternate approach would be, read the file line by line by scanner class (as described below), store those lines into any variable, say, arraylist, then appennd your new string once you have read the lines and write the whole list into a new file.
Example:
File file = new File("file.txt");
Scanner scanner = new Scanner(file).useDelimiter("\n");
String line = scanner.next();
//Store in the list
//Append the new lines
//Write the whole list into a new file

Related

Java split one line file

I have just relised that I have a file where only one line exists with a long string. This file (line) can be300MB heavy.
I would like stream some data from this string and save in another file
i.e the line from the file would look like:
String line = "{{[Metadata{"this, is my first, string"}]},{[Metadata{"this, is my second, string"}]},...,{[Metadata{"this, is my 5846 string"}]}}"
Now I would like to take 100 items from this string from one "Metadata" to another "Metadata", save it in the file and continue with the rest of the data.
So in the nutshell from one line I would like to get N files with i.e. 100 Metadata strings each
BufferedReader reader = new BufferedReader(new StringReader(line));
This is what I've got and I don't know what I can do with the reader.
Probably
reader.read(????)
but I don't know what to put inside :(
Can you please help

How to start reading lines from text from beginning again?

So i have a scanner that reads through a text file of many lines using while(file.hasNext()), however after it reaches the end of the text file how do I make it so that I can start reading lines from the beginning again for a separate while loop?
If you want to read multiple files (example, "text1.txt, text2.txt, text3.txt..etc"), this is what you can do:
Implement your file reading within a method such as:
public void readFile(String filename){
//all the code for file reading goes here
}
String[] filesToRead = new String[]{"text1.txt", "text2.txt", "text3.txt"};
for(int x=0; x<filesToRead.length; x++) //iterate through the file names
readFile(filesToRead[x]); //repeatedly invoked to read various files
Certianly, you may also save the file names within another text file, and just read from there. This way you don't even have to recompile your program when you want to change the list of files to be read.
Example:
FilesToRead.txt
text1.txt
text2.txt
text3.txt

Do something upon file exist

so i created a java program that outputs to a file (classname.java) the basic template of a java program...
/*
Nathaly Morcillo
Nov 19 2013
Header comments
*/
public class test{
public static void main String([] args){
}
}
However what i don't understand is:
After collecting the required input, check to see if the requested file (classname.java) already exists. If it does not, the program proceeds as described above. If it does exist, the program simply adds the header comments (because you probably didn’t put them in before anyhow). Hint: since you have to read from then write to the same file, try using
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
method to read in and store the contents of the whole file before writing out the file plus the new header comments.
I don't understand what to do with the scan.useDelimiter("\\Z");
What I have is:
File outputFile = new File(outputFileName);
if (outputFile.exists()) {
} else {
pout.println(
System.out.println("Contents of file");
pout.close();
}
Since this looks like homework, I'm not going to give you the answer, but I'll try to explain what's going on and give you some hints.
Scanner scan = new Scanner(file);
This creates a new Scanner object, which will allow you to read from the given file.
scan.useDelimiter("\\Z");
A Scanner object splits its input into what are called tokens. It does this by using a delimeter. Basically, it looks for anything that matches its delimeter and cuts its input at every matching point. In your case, "\\Z" is a regular expression which matches only the end of input. That causes your Scanner to read in the entire file.
String content = scan.next();
This returns the next token in your Scanner's input. Since you set the delimeter to "\\Z", this is the entire file.
Now onto the actual program. Obviously, you can't read in from a file that doesn't exist, so you'd probably only want to use your Scanner if outputFile.exists() returns true.

Java scanner not recognizing filename?

I am writing a parser that removes all punctuation from a text file and puts the words in a Map that associates each word with the number of times it occurs in the file. I use a Scanner to read the txt file, but it reads the file name instead of the actual file. For instance:
parse("./src/filename.txt")
is read as "srcfilenametxt" and is associated with a value 1. Unfortunately, I can't include more code because this is for a class assignment. How do I get it to correctly read the file?
If Scanner is constructed with a string parameter it scans the string, not the file named by the string. You'd need a line like:
Scanner in = new Scanner(new File("./src/filename.txt"));
Use bufferedreader to read a file
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));

java- read last 2 lines in a file and delete last line, then add 2 fixed string values at end of file

I want to read the last 2 lines in some files, and if the content of second last line matches a specific string, then delete the last line only.
Also, after the above operation, 2 lines of data have to be appended to the end of the modified file. I saw other questions on SO that deal with different parts of my problem, but is there an easy way of doing all of the above with minimal code, preferably in a single function? (I can combine the different functions available at SO but that would be messy...)
I would recommend you to do it "in memory". It's easy to read line by line into a List, check the last lines and update the lines and write it back to the file.
Example:
public static void main(String[] args) throws IOException {
String fileName = "test.txt";
List<String> lines = new ArrayList<String>();
// read the file into lines
BufferedReader r = new BufferedReader(new FileReader(fileName));
String in;
while ((in = r.readLine()) != null)
lines.add(in);
r.close();
// check your condition
String secondFromBottom = lines.get(lines.size() - 2);
if (secondFromBottom.matches("Hello World!")) {
lines.remove(lines.size() - 1);
lines.add("My fixed string");
}
// write it back
PrintWriter w = new PrintWriter(new FileWriter(fileName));
for (String line : lines)
w.println(line);
w.close();
}
Note: No exception handling is done in the example above... you need to handle cases where the file for example doesn't contain two lines and other problems!
If you have really big files and perfomance is an issue the way to go is to use a RandomAccessFile and read backwards looking for the line termination bytes to determine where the last two lines begin. Otherwise use dacwe's approach.
As Gandalf said you can:
take RandomAccessFile,
use method seek(long) to jump forward and read those lines. But you won't know exactly how big the jump should be.
to delete last lines you need the position of begin of last line so before reading each line store their file pointer position (method getFilePointer()). Deleting to that position you use setLength(long).
My example of reading and deleting last lines you have here:
Deleting the last line of a file with Java
Useful can be also:
Quickly read the last line of a text file?

Categories