Hi there,

I tried to to delete sorted number in each rows by reading a text file and write it to another file with a new format: such as

readfile1.text contains

1, thoman
2, tom
3, jess87
4, kelly

and so on.. I came up with this code and I don't know what's wrong with it.
I would like to remove those number and common and get like this:

thoman
tom
jess87
kelly


Here is my code:

public class test {

	public static void main (String args[])
	{

		Writer writeOut = null;

		FileInputStream in;		
		//FileinStream out;

		try
		{
		    in = new FileInputStream ("readfile1.txt");
		    DataInputStream data =new DataInputStream(in);

		    File file = new File("writefile1.txt");
		    int counts=0; 
					while(in.hasNext())
					{
						String s1 = in.nextLine();
						String strs = s1.replaceAll(args[0], "", counts);
						 writeOut.write(strs);  
						 counts++; 
				  }

		    in.close();	
		    writeOut.close();
	
				}		
	}
	}

When you call replaceAll why do you use args[0]? That is the argument of your program. You need to remove the number from inside the file.

Once you get the line from the file call the split method. Assuming that you have the line:

String [] tok = line.split(",");
// for line="1,aaaa" then the tok array will have: {"1","aaaa"} elements
// so do this:

writer.write(tok[1]);

You also need to check if the tok array has length 2 before calling tok[1]. And you need to fix the code that you use for reading and writing.

Use the BufferedReader, FileReader classes and check their APIs:

FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

String line = br.readLine();
while (line!=null) {
  // do stuf

  // write to file

  // read the next line:
  line = br.readLine();
}

And writing:

FileWriter wr = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fr);

....
bw.write("write something");
bw.newLine(); // change line
....

Also you need to close at the end the bw and br. Check their APIs

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.