0

Hi in java I am trying to split a text file [data.txt]which contains:

abc.txt  
hello.jpg  
play.mp4  
image.jpg  
text.txt

...

name of files in text form. and now i want to split this file based on file extension such as .mp3, .txt, .jpg etc using java program. because later on i want to execute that files with diffrent program based on the extention or filetype.

I have created a sample program but i am not getting how to split it based on extension

sample program:

import java.util.*;
import java.io.*;
class RF
{
   public void readFile()
   {
    try
    {
    FileInputStream fstream = new FileInputStream("data.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    while((strLine = br.readLine())!=null)
    {

        String[] splitted = strLine.split(" ");

        for( String s : splitted)
        {
            System.out.println(s);
        }


    }
    in.close();

    } catch(Exception e)
     {

     }
   }
}

public class FileSplit
{
    public static void main(String args[])
    {
        RF r = new RF();
        r.readFile();



    }
   }

I want output as :

output 
abc is a text file 
hello is a image file
play is a mp4 file
image is a image file
text is a text file

Thanks.

yogeshkmrsoni01
  • 663
  • 1
  • 7
  • 9

3 Answers3

1

Check this statement

strLine.split("-");

you are splitting on the wrong delimiter

kurumi
  • 25,121
  • 5
  • 44
  • 52
1

Try spliting by the delimiter "\\.":

String[] splitted;
while ((strLine = br.readLine()) != null) {
    splitted = strLine.split("\\.");

    System.out.println(splitted[0]);
}

Output:

abc
hello
play
image
text

Note:

The extensions are stored in splitted[1] each iteration.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

kurumi pointed out that you are using the wrong delimiter. You need to use

strLine.split(".");

Even with the "." delimiter your code will not consider special cases where filename itself has a "." in it. you are better off using a standard library like "FilenameUtils". Please refer to the following. How to get the filename without the extension in Java?

Community
  • 1
  • 1
vinay
  • 950
  • 1
  • 11
  • 27