0

I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ?

import java.io.*;


public class ConcatText{

    public static void main(String[] args){
    
        BufferedReader br = null;
        try{
            String currentLine;
            br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text"));
            
            StringBuffer text1 = new StringBuffer (br.readLine());
            StringBuffer text2 = new StringBuffer(br.readLine()); 
            text1.append(text2);
            String str = text1.toString();
            str = str.trim();
            String array[] = str.split(" ");
            StringBuffer result = new StringBuffer();
            for(int i=0; i<array.length; i++) {
               result.append(array[i]);
              }
              System.out.println(result);
            }
        catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                if(br != null){
                    br.close();
                }
                }catch(IOException e){
                    e.printStackTrace();
                    
                }
            }   
                
        }
        
    
    
    }

The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA

the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA
4
  • Does your input have spaces? Commented Jan 23, 2022 at 15:45
  • yes it has two lines of text Commented Jan 23, 2022 at 16:33
  • With spaces in them? Why are you splitting on space and reassembling a string? Commented Jan 23, 2022 at 16:37
  • String result = Files.readString(Path.of(...)).replace("\n", ""); if not. replaceAll("[ \n]+", "") if there are. Commented Jan 23, 2022 at 16:44

2 Answers 2

1

If you are using java 8 or newer, the simplest way would be:

List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);

If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this:

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
   StringBuffer text1 = new StringBuffer (br.readLine());
   StringBuffer text2 = new StringBuffer(br.readLine()); 
   // ...
}catch(IOException e){
   e.printStackTrace();
}

This way, resources will be autoclosed and you don't need to call br.close().

Sign up to request clarification or add additional context in comments.

Comments

0

Short answer, there is:

  public static void main(String[] args) {
    //this is called try-with-resources, it handles closing the resources for you
    try (BufferedReader reader = new BufferedReader(...)) {
      StringBuilder stringBuilder = new StringBuilder();
      String line = reader.readLine();
      //readLine() will return null when there are no more lines
      while (line != null) {
        //replace any spaces with empty string
        //first argument is regex matching any empty spaces, second is replacement
        line = line.replaceAll("\\s+", "");
        //append the current line
        stringBuilder.append(line);
        //read the next line, will be null when there are no more
        line = reader.readLine();
      }
      System.out.println(stringBuilder);
    } catch (IOException exc) {
      exc.printStackTrace();
    }
  }

First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example.

You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case. Also read about the methods provided by String class starting with the java doc - documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.