# Java: file contains and file ends with



## javalava (Jan 25, 2012)

I need to write a program where it reads the name of files that have been inputted by the user. It stops to scan the file names when i blank line is entered. 
If the file contains the word .txt it is supposed to print out Text File: (name of file with .txt)
and if the file contains del, it is supposed to print out Delete: (name of file with del)
So far i can get them to read the file names inputted in but when a blank line is entered the Text file: and Delete: appear but withouth the actual names of the files next to it. 
This is my code: 


String file = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter file names (blank line to end) : ");
while (scan.hasNextLine()) {
file = scan.nextLine();
if (file == null || file.length() == 0) {
break;
}
}
if (file.endsWith(".txt")) {
System.out.println("Text File: " + file);
}
if (file.contains("del")); {
System.out.println("Delete: " + file);
}
if (file.contains("del") && (file.endsWith(".txt")));{

System.out.println("Text File: " + file);
}

}
}


----------



## sepala (May 20, 2010)

Have a look at the following code. There I am using String Buffer to do the task. StringBuffer is a buffer, which can contains multiple strings. It is just like a container which is having the same kind. I am adding all the strings to the container first. Then, I read the buffer line by line using BufferedReader class. Let me know if you don't understand anything


```
import java.io.*;
import java.util.*;//Vector is inside this package..Full import is java.util.Vector;

public class Test
{
   public static void main(String[] args) throws IOException {
       
       StringBuffer buffer = new StringBuffer("");
       BufferedReader reader=null;
       
       String file = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter file names (blank line to end) : ");
while (scan.hasNextLine()) {
file = scan.nextLine();
buffer.append(file+"\n");
if (file == null || file.length() == 0) {
break;
}
}

 
    
  reader = new BufferedReader(new StringReader(buffer.toString()));
  
  while((file=reader.readLine())!=null)
  {
     
    
if (file.endsWith(".txt")) 
{
System.out.println("Text File: " + file);
}
 if (file.contains("del"))
{
System.out.println("Delete: " + file);
}
 if (file.contains("del") && (file.endsWith(".txt")))
{
System.out.println("Text File: " + file);
}
}
   }
}
```


----------

