I searched and searched over then internet and also on StackOverflow.
It is becoming a white beard.
I needed to process the contents of the clipboard copied from Excel and paste it into several text input by clicking a button on the webpage.
I do not need to do a CTRL-V in a hidden input and then every few seconds to look at the content, etc. etc.
Peremptory question:
There is no way to read the clipboard using "something"?
Tell me "NO" and I go to sleep
Carlo
Create a class file with this text
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.Toolkit;
import java.io.*;
public final class clipboardData implements ClipboardOwner {
public static void main(String... aArguments ){
clipboardData Clipboard = new clipboardData();
}
/**
* Empty implementation of the ClipboardOwner interface.
* #param aClipboard
* #param aContents
*/
#Override
public void lostOwnership(Clipboard aClipboard, Transferable aContents){
//do nothing
}
/**
* Place a String on the clipboard, and make this class the
* owner of the Clipboard's contents.
* #param aString
*/
public void setData(String aString){
StringSelection stringSelection = new StringSelection(aString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, this);
}
/**
* Get the String residing on the clipboard.
*
* #return any text found on the Clipboard; if none found, return an
* empty String.
*/
public String getData() {
String result = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//odd: the Object param of getContents is not currently used
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText =
(contents != null) &&
contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasTransferableText) {
try {
result = (String)contents.getTransferData(DataFlavor.stringFlavor);
}
catch (UnsupportedFlavorException | IOException ex){
System.out.println(ex);
ex.printStackTrace();
}
}
return result;
}
}
The code above is accessible with this functions:
Create a new clipboard editor:
clipboardData clipboardData = new clipboardData()
setData function:
clipboardData.setData(Data)
getData function:
clipboardData.getData();
Related
I am creating a program using processing(java) that outputs an SVG file for me to add it to PowerPoint and other programs.
I figured it would be a lot more convenient for the program to directly copy the generated file to my system clipboard, instead of having to copy the file from the output directory.
The trouble is that I can't find a way to set the contents of the clipboard to an SVG file. I've found ways that work with images, but not SVG. To clarify, I want the pasted file to be an SVG too because I want to edit the shapes and lines in PowerPoint afterward.
I am also open to javascript solutions which may work on the web. The goal is to be able to paste an editable collection of shapes, lines, and texts into PowerPoint.
All help is appreciated, thanks in advance!
Edit: Here is the code that works for images:
import java.awt.image.*;
import java.awt.*;
import java.awt.datatransfer.*;
import javax.imageio.*;
void setup() {
size(200, 200);
background(0);
Image img=null;
try {
img = ImageIO.read(new File("path/to/file.jpg"));//path to image file
}
catch (IOException e) {
print(e);
}
ImageSelection imageSelection = new ImageSelection(img);
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.getSystemClipboard().setContents(imageSelection, null);
}
void draw() {
}
public class ImageSelection implements Transferable {
private Image image;
public ImageSelection(Image image) {
this.image = image;//added on
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (flavor.equals(DataFlavor.imageFlavor) == false) {
throw new UnsupportedFlavorException(flavor);//usually with transferable
}
return image;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.imageFlavor);//usually with transferable
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {
DataFlavor.imageFlavor//usually with transferable
};
}
}
There is a bit of confusion with the code you posted: so far it looks like for some reason you want to load an image and copy that to the clipboard, not an SVG.
If you want to copy an SVG to the clipboard for PowerPoint there are a few hoops to jump through:
Use the PShapeSVG source code to understand to get the SVG markup
Use the right MIME type: I simply tried this solution
Putting it together:
import processing.svg.*;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
void setup(){
PGraphicsSVG svg = (PGraphicsSVG)createGraphics(300,300,SVG);
svg.beginDraw();
svg.background(#4db748);
svg.noFill();
svg.strokeWeight(27);
int a = 80;
int b = 220;
svg.line(a,a,b,b);
svg.line(a,b,b,a);
svg.line(a,a,b,a);
svg.line(a,b,b,b);
svg.ellipse(150, 150, 250, 250);
copyToClipboard(svg);
// normally you would call endDraw, but this will obviously throw an error if you didn't specify a filename in createGraphics()
//svg.endDraw();
println("svg copied to clipboard");
exit();
}
String getSVGString(PGraphicsSVG svg){
// make a binary output stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
// make a writer for it
Writer writer = PApplet.createWriter(output);
// same way the library writes to disk we write to the byte array stream
try{
((SVGGraphics2D) svg.g2).stream(writer, false);
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
}
// convert bytes to an UTF-8 encoded string
return new String( output.toByteArray(), StandardCharsets.UTF_8 );
}
void copyToClipboard(PGraphicsSVG svg){
// get the SVG markup as a string
String svgString = getSVGString(svg);
println(svgString);
// access the system clipboard
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
// get an binary clipboard with the correct SVG MIME type
SvgClip strSVG = new SvgClip(svgString);
// commit the clipboard encoded SVG to clipboard
clip.setContents(strSVG, null);
}
// blatant copy/adapation of https://stackoverflow.com/questions/33726321/how-to-transfer-svg-image-to-other-programs-with-dragndrop-in-java
class SvgClip implements Transferable{
String svgString;
DataFlavor svgFlavor = new DataFlavor("image/svg+xml; class=java.io.InputStream","Scalable Vector Graphic");
DataFlavor [] supportedFlavors = {svgFlavor};
SvgClip(String svgString){
this.svgString = svgString;
SystemFlavorMap systemFlavorMap = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
systemFlavorMap.addUnencodedNativeForFlavor(svgFlavor, "image/svg+xml");
}
#Override public DataFlavor[] getTransferDataFlavors(){
return this.supportedFlavors;
}
#Override public boolean isDataFlavorSupported(DataFlavor flavor){
return true;
}
#Override public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException{
return new ByteArrayInputStream(svgString.getBytes(StandardCharsets.UTF_8));
}
}
Note Call copyToClipboard(svg) after your last drawing command, but before PGraphicsSVG's endDraw() call (otherwise it will return an empty SVG document)
The result in PowerPoint:
I am using Java Swing v2 by Robinson & Vorobiev as a framework to understand JTree's. I have redone the source code from [https://www.manning.com/books/swing-second-edition][1] Chapter17/4 to include better encapsulating and information hiding. The rename EditorListener (CellEditorListener) had a bug in that java.io.File.rename() did not work but java.nio.Files.move() does. I then included checks for an existing directory and for a failure to move.
The issue is that in these two failures the only thing needed is to update the GUI so that the original value of the node is displayed. The node data does not change and does not need to be updated. The display area update I know how to do. But I do not know how to update only the displayed node. The only thing that seems to work is to replace the tree node with a new version of itself.
Code is below. Any help will be greatly appreciated.
/**
* Copyright 1999-2002 Matthew Robinson and Pavel Vorobiev.
* All Rights Reserved.
*
* ===================================================
* This program contains code from the book "Swing"
* 2nd Edition by Matthew Robinson and Pavel Vorobiev
* http://www.spindoczine.com/sbe
* ===================================================
*
* The above paragraph must be included in full, unmodified
* and completely intact in the beginning of any source code
* file that references, copies or uses (in any way, shape
* or form) code contained in this file.
*/
/*
Source Code: https://www.manning.com/books/swing-second-edition Chapter17/4
*/
package ch17.v4;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
/**
*
* #author Java Swing vrs. 2
*/
public class EditorListener implements CellEditorListener {
protected Tree m_tree;
protected DefaultTreeCellEditor m_editor;
protected DefaultTreeModel m_model;
protected JTextField m_display;
public EditorListener( DefaultTreeCellEditor m_editor
, Tree m_tree
, DefaultTreeModel m_model
, JTextField m_display) {
this.m_editor = m_editor;
this.m_tree = m_tree;
this.m_model = m_model;
this.m_display = m_display;
} // EditorListener()
#Override
public void editingStopped(ChangeEvent e) {
if (m_tree.m_editingNode != null) {
String newName = m_editor.getCellEditorValue().toString();
File dir = m_tree.m_editingNode.getFile();
File newDir = new File(dir.getParentFile(), newName);
m_tree.m_editingNode = null; // moved
/******************************** New Code ********************************/
if(newDir.exists()) {
int value = JOptionPane.showConfirmDialog( null // parent
, "Do you wnat to overwrite>" // message
, newName // title
, JOptionPane.YES_NO_OPTION // optionType
, JOptionPane.WARNING_MESSAGE); // messageType
if (value == JOptionPane.NO_OPTION) {
update(dir);
return;
}
}
try {
Path move = Files.move( dir.toPath() // from
, newDir.toPath() // to
, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException exception) {
JOptionPane.showConfirmDialog( null // parent
, "Unable to rename" // message
, newName // title
, JOptionPane.OK_OPTION // optionType
, JOptionPane.ERROR_MESSAGE); // messageType
System.out.println( "[ERROR] Unable to rename "
+ dir.toString() + " "
+ exception.getMessage());
update(dir);
return;
}
/**************************************************************************/
// dir.renameTo(newDir);
// Update tree
update(newDir);
}
}
private void update( File dir) { // correctly displays node
TreePath path = m_tree.getSelectionPath();
DefaultMutableTreeNode node = Tree.getTreeNode(path);
IconData idata = new IconData( DirTree.ICON_FOLDER
, DirTree.ICON_EXPANDEDFOLDER
, new FileNode(dir));
node.setUserObject(idata);
m_model.nodeStructureChanged(node);
m_display.setText(dir.getAbsolutePath());
} // void update( File dir)
#Override
public void editingCanceled(ChangeEvent e) {
m_tree.m_editingNode = null;
}
private void restoreName() {
} // void restoreName()
} // class EditorListener implements CellEditorListener
In my Java code I use a FileVisitor to traverse a filesystem and creating a structure of Paths, then later on this is converted to a json object for rendering in html.
Running on Windows it runs okay even against a linux filesystem, running on Linux against the same (now local) filesystem it fails to render special characters properly when call toString() on a path
i.e Windows debug output
CreateFolderTree:createJsonData:SEVERE: AddingNode(1):Duarte Lôbo- Requiem
and html displays ok as
Duarte Lôbo- Requiem
but linux debug output gives
CreateFolderTree:createJsonData:SEVERE: AddingNode(1):Duarte L??bo- Requiem
and html displays as two black diamond with question mark in them instead of the ô char
Why is this happening, the Paths are provided by the the FileVisitor class so must be getting constructed properly (i.e I am not hacking it myself) , and then i just call toString() on the path.
Is it a fonts problem, I have had some issues with fonts on the linux system but here I am just returning Strings to the html so cannot see a conection.
Probably an encoding issue, but I cant see a place where I am explicitly setting an encoding
Bulk of code below, debugging showing invalid output for linux is in the createJsonData() method
Edit:I have fixed the logging issue so that the output is written as UTF-8
FileHandler fe = new FileHandler(logFileName, LOG_SIZE_IN_BYTES, 10, true);
fe.setEncoding(StandardCharsets.UTF_8.name());
So we now see Windows is outputting correctly
CreateFolderTree:createJsonData:SEVERE: AddingNode(1):Duarte Lôbo- Requiem
but Linux is outputting
CreateFolderTree:createJsonData:SEVERE: AddingNode(1):Duarte L��bo- Requiem
and if I view this in HexEditor it gives this output for L��bo
4C EF BF BD EF BF BD 62 6F
Edit:Partial Solution
I came across What exactly is sun.jnu.encoding?
and found it was recommended to add this
-Dsun.jnu.encoding=UTF-8
and it worked files were now displayed okay
Unfortunately if user then clicked on such a file and sent back to server I now get this error
java.lang.NullPointerException
at java.base/sun.nio.fs.UnixPath.normalizeAndCheck(Unknown Source)
at java.base/sun.nio.fs.UnixPath.<init>(Unknown Source)
at java.base/sun.nio.fs.UnixFileSystem.getPath(Unknown Source)
at java.base/java.nio.file.Paths.get(Unknown Source)
at com.jthink.songkong.server.callback.ServerFixSongs.configureFileMapping(ServerFixSongs.java:59)
at com.jthink.songkong.server.callback.ServerFixSongs.startTask(ServerFixSongs.java:88)
at com.jthink.songkong.server.CmdRemote.lambda$null$36(CmdRemote.java:107)
I tried adding -Dfile.encoding=UTF-8 both in addtion or instead of the jnu option and that didnt help , the jnu option was the one I needed.
I shoudn't have to add this undocumented sun-jnu-encoding option so it seems to be that the server is broken in some way ?
Code
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jthink.songkong.analyse.analyser.Counters;
import com.jthink.songkong.analyse.general.Errors;
import com.jthink.songkong.cmdline.SongKong;
import com.jthink.songkong.fileloader.RecycleBinFolderNames;
import com.jthink.songkong.server.fs.Data;
import com.jthink.songkong.server.fs.PathWalker2;
import com.jthink.songkong.server.fs.State;
import com.jthink.songkong.ui.MainWindow;
import com.jthink.songkong.ui.progressdialog.FixSongsCounters;
import spark.Request;
import spark.Response;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
/**
* Count the number of files that can be loaded, for information purposes only
*/
public class CreateFolderTree
{
private Path treeRoot;
Set<Path> keys = new HashSet<Path>();
public static class VisitFolder
extends SimpleFileVisitor<Path>
{
private Set<Path> keys;
private Integer maxDepth;
private int depth;
public VisitFolder(Set<Path> keys, Integer maxDepth)
{
this.keys=keys;
this.maxDepth = maxDepth;
}
/**
*
* #param dir
* #param attrs
* #return
* #throws IOException
*/
/*
* Ignore some dirs
* #param dir
* #param attrs
* #return
* #throws IOException
*/
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
try
{
if (dir.toFile().getName().equals(".AppleDouble"))
{
return FileVisitResult.SKIP_SUBTREE;
}
else if (dir.toString().equals("/proc"))
{
return FileVisitResult.SKIP_SUBTREE;
}
else if (dir.toString().equals("/dev"))
{
return FileVisitResult.SKIP_SUBTREE;
}
else if (RecycleBinFolderNames.isMatch(dir.toFile().getName()))
{
MainWindow.logger.log(Level.SEVERE, "Ignoring " + dir.toString());
return FileVisitResult.SKIP_SUBTREE;
}
else if (dir.toString().toLowerCase().endsWith(".tar"))
{
return FileVisitResult.SKIP_SUBTREE;
}
depth++;
if(depth > maxDepth)
{
depth--;
return FileVisitResult.SKIP_SUBTREE;
}
keys.add(dir);
return super.preVisitDirectory(dir, attrs);
}
catch(IOException e)
{
MainWindow.logger.warning("Unable visit dir:"+dir + ":"+e.getMessage());
return FileVisitResult.SKIP_SUBTREE;
}
}
/**
*
* Tar check due to http://stackoverflow.com/questions/14436032/why-is-java-7-files-walkfiletree-throwing-exception-on-encountering-a-tar-file-o/14446993#14446993
* SONGKONG-294:Ignore exceptions if file is not readable
*
* #param file
* #param exc
* #return
* #throws IOException
*/
#Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
{
if (file.toString().endsWith(".tar")) {
//We dont log to reports as this is a bug in Java that we are handling not a problem in SongKong
MainWindow.logger.log(Level.SEVERE, exc.getMessage());
return FileVisitResult.CONTINUE;
}
try
{
FileVisitResult result = super.visitFileFailed(file, exc);
return result;
}
catch(IOException e)
{
MainWindow.logger.warning("Unable to visit file:"+file + ":"+e.getMessage());
return FileVisitResult.CONTINUE;
}
}
/**
* SONGKONG-294:Ignore exception if folder is not readable
*
* #param dir
* #param exc
* #return
* #throws IOException
*/
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException
{
depth--;
try
{
FileVisitResult result = super.postVisitDirectory(dir, exc);
return result;
}
catch(IOException e)
{
MainWindow.logger.warning("Unable to count files in dir(2):"+dir);
return FileVisitResult.CONTINUE;
}
}
}
public CreateFolderTree(Path treeRoot)
{
this.treeRoot = treeRoot;
}
public String start(int depth)
{
VisitFolder visitFolder;
try
{
if(treeRoot==null)
{
for (Path path : FileSystems.getDefault().getRootDirectories())
{
visitFolder = new VisitFolder(keys, depth);
Files.walkFileTree(path, visitFolder);
}
}
else
{
visitFolder = new VisitFolder(keys, depth);
Files.walkFileTree(treeRoot, visitFolder);
}
PathWalker2 pw = new PathWalker2();
for (Path key : keys)
{
//SONGKONG-505: Illegal character in Filepath problem prevented reportFile creation
try
{
pw.addPath(key);
}
catch (InvalidPathException ipe)
{
MainWindow.logger.log(Level.SEVERE, ipe.getMessage(), ipe);
}
}
Gson gson = new GsonBuilder().create();
return gson.toJson(createJsonData(pw.getRoot()));
}
catch (Exception e)
{
handleException(e);
}
return "";
}
public void handleException(Exception e)
{
MainWindow.logger.log(Level.SEVERE, "Unable to count files:"+e.getMessage(), e);
Errors.addError("Unable to count files:"+e.getMessage());
MainWindow.logger.log(Level.SEVERE, e.getMessage());
Counters.getErrors().getCounter().incrementAndGet();
SongKong.refreshProgress(FixSongsCounters.SONGS_ERRORS);
}
/**
* Add this node and recursively its children, returning json data representing the tree
*
* #param node
* #return
*/
private Data createJsonData(PathWalker2.Node node)
{
Data data = new Data();
if(node.getFullPath()!=null)
{
data.setId(node.getFullPath().toString());
if(node.getFullPath().getFileName()!=null)
{
MainWindow.logger.severe("AddingNode(1):"+node.getFullPath().getFileName().toString());
data.setText(node.getFullPath().getFileName().toString());
}
else
{
MainWindow.logger.severe("AddingNode(2):"+node.getFullPath().toString());
data.setText(node.getFullPath().toString());
}
}
else
{
try
{
data.setText(java.net.InetAddress.getLocalHost().getHostName());
data.setId("#");
State state = new State();
state.setOpened(true);
data.setState(state);
}
catch(UnknownHostException uhe)
{
data.setText("Server");
}
}
//Recursively add each child folder of this node
Map<String, PathWalker2.Node> children = node.getChildren();
if(children.size()>0)
{
data.setChildren(new ArrayList<>());
for (Map.Entry<String, PathWalker2.Node> next : children.entrySet())
{
data.getChildren().add(createJsonData(next.getValue()));
}
}
else
{
data.setBooleanchildren(true);
}
return data;
}
public static String createFolderJsonData(Request request, Response response)
{
if(Strings.nullToEmpty(request.queryParams("id")).equals("#"))
{
CreateFolderTree cft = new CreateFolderTree(null);
String treeData = cft.start(1).replace("booleanchildren", "children");
return treeData;
}
else
{
CreateFolderTree cft = new CreateFolderTree(Paths.get(request.queryParams("id")));
String treeData = cft.start(2 ).replace("booleanchildren", "children");
return treeData;
}
}
}
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/** Constructs a tree of folders based on a list of filepaths
*
* i.e a give it a list if all folder that contain files that have been modified and it creates a hierachy
* that can then be used to generate a data structure for use by jstree
*
*/
public class PathWalker2
{
private final Node root;
public PathWalker2()
{
root = new Node();
}
public Node getRoot()
{
return root;
}
/**
* Represent a node on the tree (may/not have children)
*/
public static class Node
{
//Keyed on name and node
private final Map<String, Node> children = new TreeMap<>();
private Path fullPath;
public Node addChild(String name)
{
if (children.containsKey(name))
return children.get(name);
Node result = new Node();
children.put(name, result);
return result;
}
public Map<String, Node> getChildren()
{
return Collections.unmodifiableMap(children);
}
public void setFullPath(Path fullPath)
{
this.fullPath = fullPath;
}
public Path getFullPath()
{
return fullPath;
}
}
/**
* #param path
*/
public void addPath(Path path)
{
Node node = root.addChild((path.getRoot().toString().substring(0, path.getRoot().toString().length() - 1)));
//For each segment of the path add as child if not already added
for (int i = 0; i < path.getNameCount(); i++)
{
node = node.addChild(path.getName(i).toString());
}
//Set full path of this node
node.setFullPath(path);
}
}
So as always with encoding problems this has been a lot of work to debug. Not only are there a lot of different things that affect it, they also affect it at different times, so the first task is always to check where does it go wrong first.
As the deal with the � showed, once it goes wrong, it can then go more wrong and if you try to debug starting from the end result, it's like peeling layers from a rotten onion.
In this case the root of the problem was in the OS locale, which was set to POSIX. This old standard makes your OS act like it's from the 70's, with ASCII encoding and other outdated details. The ASCII encoding will prevent the OS from understanding filenames, text or anything containing more exotic characters. This causes weird issues because the JVM is doing just fine by itself, but any time it communicates with the OS (printing to a text file, asking to open a file with a certain name) there's a chance of corruption because the OS doesn't understand what the JVM is saying.
It's like someone is talking to you and every once in a while he puts a word of Chinese in there. You're writing down what he says in English, but every Chinese word you replace with "Didn't understand???".
The locale (in /etc/default/locale) usually contains sane defaults, but as we saw here, you can't always trust that. For any modern systems you'll want locale values like en_EN.UTF-8. You never want to see POSIX there in this day and age.
For html you either need to set a proper charset matching your needs or better stick with ASCII and use html-encoding for all non-ASCII characters.
This works even if no specific charset is defined for you html display.
https://en.wikipedia.org/wiki/Unicode_and_HTML
It seems that your debug output goes through multiple conversions between charsets. The text you send to the console seems to be converted to bytes using UTF-8 as encoding resulting into the conversion from ô to ô. Then there seems to be another conversion from the byte-data back into characters using the system's charset. Windows' console uses cp1252 as charset while Linux has different settings on a per installation basis. In your case it seems to be ASCII leading to the conversion to the two ? for the UTF-8 encoded data because these bytes have values that aren't defined in ASCII.
I don't know the logging framework you're using or what the specific setup of the Logger is you're using, so I can't tell you how to fix that, but for the Linux-variant, you might check the console's charset and change it to UTF-8 to see if that has the desired effect.
public class InputFileData {
/**
* #param inputFile a file giving the data for an electronic
* equipment supplier’s product range
* #return an array of product details
* #throws IOException
*/
public static Product [] readProductDataFile(File inputFile)
throws IOException{
// YOUR CODE HERE
}
This code is meant to read a text file and store the data in an array of type Product[]. I know how to read in a text file and have it sort it into an array, but I've never seen code laid out in this fashion before (specifically "public static Product[]", and I'm unsure how to work with "(File inputfile)". I've looked all over the place but can't find any examples of anything like this. Could someone explain this to me?
EDIT
package electronicsequipmentdemo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.System.out;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author George
*/
public class InputFileData {
/**
* #param inputFile a file giving the data for an electronic
* equipment supplier’s product range
* #return an array of product details
* #throws IOException
*/
public static Product [] readProductDataFile(File inputFile)
throws IOException{
Product[] productName;
try {
FileReader fr = new FileReader("productDataFile.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
Product[] list = str.split("/");
Arrays.toString(list);
productName = list[1];
return productName;
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
return null;
}
This gives the following errors:
Product[] list = str.split("/"); incompatible types: String[] cannot be converted to product[]
productName = list[1]; incompatible types: Product cannot be converted to Product[]
I've tried lots of things, but without knowing how this sort of class is meant to work (I've never seen a method written out like this), combined with the fact I've been trying to make it work for a solid two days, I've probably got everything wrong. I'm desperate to learn how to do this, help would really be appreciated.
This is a static method. See this turorial (or a lot of others): http://www.programmingsimplified.com/java/source-code/java-static-method-program
Java static method
Java static method program: static methods in Java can be called
without creating an object of class. Have you noticed why we write
static keyword when defining main it's because program execution
begins from main and no object has been created yet. Consider the
example below to improve your understanding of static methods.
Please try the below code
package electronicsequipmentdemo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.System.out;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author George
*/
public class InputFileData {
/**
* #param inputFile a file giving the data for an electronic
* equipment supplier’s product range
* #return an array of product details
* #throws IOException
*/
public static Product [] readProductDataFile(File inputFile)
throws IOException{
Product[] productList=new Product[100];
int i=0;
try {
FileReader fr = new FileReader("productDataFile.txt");
BufferedReader br = new BufferedReader(fr);
String str;
String[] list= new String[100];
while ((str = br.readLine()) != null) {
list = str.split("/");
for(String name:list){
Product product=new Product();
product.setProductName(name);
if(i<100){
productList[i]=product;
i++;
}
}
}
br.close();
return productList;
}
} catch (IOException e) {
out.println("File not found");
}
return null;
}
The idea is that the read line method will return you a string, when you split this string using your delimiter you get an array of strings now you have to create a Product object using the setter method of the Product class(which you know i guess) the you need to add the product objet to the ProductList array here i have assumed that there are not more than 100 product objects and 100 names in a line of the file you are trying to read.
How to insert a palette component of the jar file?
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: user
* Date: 05.07.13
* Time: 17:51
* To change this template use File | Settings | File Templates.
*/
public class ImageViewerBean extends JLabel {
private File file=null;
int XPREFSIZE=200;
int YPREFSIZE=200;
public ImageViewerBean(){
setBorder(BorderFactory.createEtchedBorder());
}
public void setFileName(String fileName)
{
File file1=new File(fileName);
try {
setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
file=null;
setIcon(null);
}
}
public String getFileName(){
if (file!=null)
return file.getPath();
else
return null;
}
public Dimension getPreferredSize(){
return new Dimension(XPREFSIZE,YPREFSIZE);
}
}
Manifest:
Manifest-Version: 1.0
Name: C:\Users\user\IdeaProjects\AWTLearn\src\ImageViewerBean.java
Java-Bean: True
In the manifesto, all strictly no extra spaces at the end of an empty string.
Please check Adding GUI Components and Forms to the Palette on the IDEA web help page.