Reputation: 51
I have a text file which gets created by a batch script where the field position are always the same. Within that file, I want to go to a specific position and add a field to it.
For example, suppose my file has only two lines and has the following fields:
number customer_id account_no address price plan
number customer_id account_no address price plan
I want to add an extra field between address and price so the new file will look similar to this:
number customer_id account_no address newfield price plan
number customer_id account_no address newfield price plan
I couldn't find any Utility
class that can go to a specific position of a line in a file and write to it.
I could do it the tedious way of placing the fields to an array including the whitespace and spitting it out field by field to a new file, however, that was too cumbersome and very tedious (since it has more than 90 fields) and was wondering if there is an easier way.
Upvotes: 0
Views: 671
Reputation: 17454
I could do it the tedious way of placing the fields to an array including the whitespace and spitting it out field by field to a new file, however, that was too cumbersome and very tedious (since it has more than 90 fields) and was wondering if there is an easier way.
If you were to do it by using Java, there is no way you can insert data in between text. It only allows you to append to the end of the file.
Anyway if you need to insert a new column and maintain the format consistency of the entire data file, you need to insert a whitespace for those rows without a value, hence rewriting all rows is still inevitable.
I couldn't find any Utility class that can go to a specific position of a line in a file and write to it
If you couldn't find one, you can write one yourself. It is actually not that tedious. Just write a utility class yourself, so you can use it in future.
//A brief example..
public final class FileUtility{
private static String filepath;
public static void setFilePath(String filepath){
FileUtility.filepath = filepath;
}
public static int searchField (String fieldname, int lineNo){
//return position of given field namein a specific line
}
public static void insertDataAt (String data, int column){
//return position of given field
}
public static boolean dataExist(String data, int lineNo){
//return true if given data exist at given line number
}
}
Upvotes: 1
Reputation: 4634
Forget about appending to the middle of the file. Files are sequence of bytes, so, you need to process all the bytes after insert points first to move them N bytes forward to create a place for your modification. This costs more than processing file on the fly and writing new lines to another file.
Upvotes: 0