How to Access Clipboard data using Java in Windows? - java

I want to Access Clipboard data/text in my Java Program in Windows 10 system targeted program. Any code snippets or Class that is used to access the clipboard data?

This code snippet is for accessing and printing the clipboard data in Java:
import java.awt.datatransfer.*;
import java.awt.*;
/**
* Demo to access System Clipboard
*/
public class SystemClipboardAccess {
public static void main(String args[]) throws Exception {
// Create a Clipboard object using getSystemClipboard() method
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
// Get data stored in the clipboard that is in the form of a string (text)
System.out.println(c.getData(DataFlavor.stringFlavor));
}
}

Use Toolkit#getSystemClipboard:
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
public static String readClipboard() {
return (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
}

Related

Cannot read the array length because "<local1>" is null

I am making a stock market simulator app in java, and there is an issue in the deleteHistoryFiles() method. It says that array is null. However, I have no idea what array this error is talking about.
Here's the code (I've deleted some methods to save space):
package stock.market.simulator;
import java.util.Random;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StockMarketSimulator {
// Path to where the files are stored for rate history
// USE WHEN RUNNING PROJECT IN NETBEANS
//public static final String HISTORYFILEPATH = "src/stock/market/simulator/history/";
// Path to history files to be used when executing program through jar file
public static final String HISTORYFILEPATH = "history/";
public static void main(String[] args) throws IOException {
accountProfile accProfile = accountCreation();
stockProfile[][] stockProfile = createAllStocks();
deleteHistoryFiles(new File(HISTORYFILEPATH));
createHistoryFiles(stockProfile);
mainWindow window = new mainWindow(accProfile, stockProfile);
recalculationLoop(stockProfile, window);
}
// Procedure to create the history files
public static void createHistoryFiles(stockProfile[][] stocks) throws IOException {
String fileName;
FileWriter fileWriter;
for (stockProfile[] stockArray : stocks) {
for (stockProfile stock : stockArray) {
fileName = stock.getProfileName() + ".csv";
fileWriter = new FileWriter(HISTORYFILEPATH + fileName);
}
}
}
// Procedure to delete the history files
public static void deleteHistoryFiles(File directory) {
for (File file : directory.listFiles()) {
if (!file.isDirectory()) {
file.delete();
}
}
}
}
I got the same exception in exactly the same scenario. I tried to create an array of files by calling File.listFiles() and then iterating the array.
Got exception Cannot read the array length because "<local3>" is null.
Problem is that the path to the directory simply does not exist (my code was copied from another machine with a different folder structure).
I don't understand where is <local1> (sometimes it is <local3>) comes from and what does it mean?
It should be just like this: Cannot read the array length because the array is null.
Edit (answering comment) The sole interesting question in this question is what is a <local1>
My answer answers this question: <local1> is just an array created by File.listFiles() method. And an array is null because of the wrong path.

jsoup Not Catching Full Webpage

Trying to make a super simple bit of code using jsoup to see if a webpage contains a specific word (checks to see the availability of a class to take in-residence). jsoup seems to be catching lots of the webpage specified, but won't capture all of it - specifically the area I'm interested in. Is there a reason for this? Am I doing something wrong?
import org.jsoup.Jsoup;
import java.io.IOException;
import org.jsoup.nodes.Document;
public class main {
public static void main(String[] args) throws IOException{
String html = Jsoup.connect("https://www.afit.edu/CE/Course_Desc.cfm?p=WENG%20481").maxBodySize(0).get().html();
System.out.print(html);
if (html.contains("Resident")) {
System.out.print("\nAVAILABLE!");
}
}
}

How to download an online file directory (localhost) using Java

I have a static file server at "localhost:8888/fileserver".
I am trying to write a program in java to download the files from the server. The file server consists of three folders, therefore I am trying to write a script that automatically goes through the directory and copies it to my computer.
I know there is a wget function for linux that accomplishes this recursively. Is there a way to do this in Java?
Please could you advise on how I should go about doing this or proceed.
Thank you
Below is a code to go through an online directory and return back all the links needed to download.
After that I just need to download each individual link.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class WebCrawler {
//Created a global list variable to save the links
static List<String> createList = new ArrayList<String>();
public static void main(String[] args) throws IOException {
String url = "http://localhost:8888";
System.out.println(myCrawler(url)+"\n"+"Size: "+myCrawler(url).size());
}
public static List<String> myCrawler(String url) throws IOException{
//Creates an open connection to a link
Document doc = Jsoup.connect(url).ignoreContentType(true).get();
Elements links = doc.select("a[href]");
//Recursively iterates through all the links provided on the initial url
for (Element i : links) {
String link = print("%s", i.attr("abs:href"));
if (link.endsWith("/")){myCrawler(link);} //Recursive part, calls back on itself
else {createList.add(link);}
}
return createList;
}
//Translates the link into a readable string object
private static String print(String msg, Object... args){return String.format(msg, args);}
}

passing argument to WordCram code

I have the following question: I am trying to execute the usConstitution wordcram example (code follows) and if provided as is the code executes in eclipse, the applet starts and the word cloud is created. (code follows)
import processing.core.*;
//import processing.xml.*;
import wordcram.*;
import wordcram.text.*;
import java.applet.*;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;
import java.awt.event.FocusEvent;
import java.awt.Image;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.zip.*;
import java.util.regex.*;
public class usConstitution extends PApplet {
/*
US Constitution text from http://www.usconstitution.net/const.txt
Liberation Serif font from RedHat: https://www.redhat.com/promo/fonts/
*/
WordCram wordCram;
public void setup() {
size(800, 600);
background(255);
colorMode(HSB);
initWordCram();
}
public void initWordCram() {
wordCram = new WordCram(this)
.fromTextFile("http://www.usconstitution.net/const.txt")
.withFont(createFont("https://www.redhat.com/promo/fonts/", 1))
.sizedByWeight(10, 90)
.withColors(color(0, 250, 200), color(30), color(170, 230, 200));
}
public void draw() {
if (wordCram.hasMore()) {
wordCram.drawNext();
}
}
public void mouseClicked() {
background(255);
initWordCram();
}
static public void main(String args[]) {
PApplet.main(new String[] { "--bgcolor=#ECE9D8", "usConstitution" });
}
}
My problem is the following:
I want to pass through main (which is the only static class) an argument so as to call the usConstitution.class from another class providing whichever valid filename I want in order to produce its word cloud. So how do I do that? I tried calling usConstitution.main providing some args but when I try to simply print the string I just passed to main (just to check if it is passed) I get nothing on the screen. So the question is How can I pass an argument to this code to customize .fromTextFile inside initWordCram ?
Thank you a lot!
from: https://wordcram.wordpress.com/2010/09/09/get-acquainted-with-wordcram/ :
Daniel Bernier says:
June 11, 2013 at 1:13 am
You can’t pass command-line args directly to WordCram, because it has no executable.
But you can make an executable wrapper (base it on the IDE examples that come with WordCram), and it can read command-line args & pass them to WordCram as needed.
FYI, it’ll still pop up an Applet somewhere – AFAIK, you can’t really run Processing “headless.” But that’s usually only a concern if you’re trying to run on a server.

Set Clipboard Contents

I am trying to figure out why setting the contents of the system clipboard won't work for me. I programmatically set the clipboard contents. When i use the output part of the code, it works. However, when i try copy/pasting in any text editor, it is blank.
hovercraft edit, code from github:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws HeadlessException,
UnsupportedFlavorException, IOException {
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection("hi there"), null);
System.out.println(((String) Toolkit.getDefaultToolkit()
.getSystemClipboard().getData(DataFlavor.stringFlavor)));
}
}
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Clipboard;
public class tester{
public static void main(String[] args){
// from string to clipboard
StringSelection selection = new StringSelection("hi");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
}
This program does it. It will set the String "hi" to clipboard. You can change it to a variable.
Linux cut and paste is a bit weird these days, because there are at least two different ways of doing it. In short, sometimes it's better to just paste with the middle button, and other times it's better to control-v, and sometimes neither seems to work.
Running autocutsel as a background process seems to help.
http://www.nongnu.org/autocutsel/

Categories