Read text file and copy your lines in Clipboard using Toolkit

Asked

Viewed 80 times

0

I have a text file (txt) with 1000 lines, and I wanted to include them in the Clipboard. But from the examples I tested, only the last line is being copied to the Clipboard.

I looked for something like apend for Clipboard but not found. How can I do that?

Follow my attempt:

public class teste {
    public static void main(String[] args) throws Throwable {

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File("G:\\Arquivos"));
        FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "text");
        fileChooser.setFileFilter(filter);      
        fileChooser.showOpenDialog(null);
        File selectedFile = fileChooser.getSelectedFile();

        FileInputStream fs= new FileInputStream(selectedFile.getAbsolutePath());
        BufferedReader br2 = new BufferedReader(new InputStreamReader(fs));

        int bo = 0;

        while(bo < 1){
            try{
                StringSelection selection = new StringSelection(br2.readLine());
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                clipboard.setContents(selection, selection);

            }catch(java.lang.IllegalStateException e){              
                bo = 1;
                br2.close();
                fs.close();
            }
        }
    }
}
  • 1

    How do we know the packs of these classes there? ?

  • 1

    It would be the case to accumulate everything in a string and make the setContents out of the loop.

1 answer

1


You can simplify using java-7 classes, such as the class Files which facilitates working with reading text files, transforming into a List strings with the lines of the file. Then, just use a loop to concatenate the lines with StringBuffer.

Just be careful with the excess of information sent to the Clipboard, do not forget that it is limited by the computer’s memory and the more data you send, the greater the use of memory to keep that data available.

Also, it is worth drawing attention to some points that I modified that you are not doing the right way:

  • never throw anything to Throwable, what is the need? Some classes you are using, in fact, have checked exceptions, if you do not want to treat, throw the exception in specific of that class, and not Exception and even less for this one. In the case of the code below, I preferred to use multi-catch, make exception forward is the same as "push the problem with the belly", unless you know what you’re doing and you have a plausible reason for it;

  • You are using a component of the java-swing api, so it is necessary to dispatch to a specific thread, called EDT.

The code with the changes goes like this:

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

public class LerTxtClipBoardTest {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File("G:\\Arquivos"));
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt");
            fileChooser.setFileFilter(filter);
            fileChooser.showOpenDialog(null);
            File selectedFile = fileChooser.getSelectedFile();

            try {
                List<String> txtLines = Files.readAllLines(selectedFile.toPath());

                StringBuffer sb = new StringBuffer();

                for (String temp : txtLines) {
                    sb.append(temp);
                    sb.append(System.lineSeparator());
                }

                StringSelection selection = new StringSelection(sb.toString());
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                clipboard.setContents(selection, selection);


            } catch (IOException | UnsupportedFlavorException e) {
                e.printStackTrace();
            }
        });

    }
}

Working:

inserir a descrição da imagem aqui

I used an excerpt from the randomized text generator lorem ipsum to fill the file.

  • Thank you very much! I will test

  • @vbajr if the answer helped you, you can accept it by clicking on v on the left side. Thus, it will serve as a reference for others with a similar problem.

  • Thank you very much Friend, It served perfectly, copied all 5,000 lines for the Clipboard. Thanks very much. I am very Newbie and I have only basic notion.

  • Valeu Articuno L!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.