Tuesday, June 16, 2009

Program to cut text file from character position x to y

I was searching for a windows equivalent to the Unix "cut" command. However, none could be found. So this java program will eventually do all that the Unix "cut" command does and more.

The functionality i required was to cut a text file between two given positions.Although this seems simple enough, notepad, textpad etc. don't have this facility. Hope this initial version will help those of you who want to cut a text file between two points. The program does not consider newline characters, but tab, space etc.. are considered while counting.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Cut {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(args[0]);
out = new FileOutputStream("cutoutput.txt");
int c,count=0,llim=Integer.parseInt(args[1]),ulim=Integer.parseInt(args[2]);

while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =count-1;}
count++;
if(count>=llim && count<=ulim){
//System.out.println((char)c);
out.write(c);}
}
System.out.println("Total characters between range is "+(ulim-llim));
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

3 comments:

Anonymous said...

Good post and this post helped me alot in my college assignement. Gratefulness you on your information.

Anonymous said...

You can install cygwin and get most of the *nix commands, including cut. Did you try that?

Anonymous said...

Did you try installing cygwin? Cygwin brings a *nix env to your windows machine, most of the software, commands on linux/unix are available on windows - yes including cut