I created a class of type JTextPane in my text editor program. it has a subclass of text and richtext that inherts from my main JTextPaneClass. However, I'm unable to load RTF into my richtext because the method of reading fileinput stream isn't in the superclass JTextPane. So how do I read rich text into jtextpane? This seems very simple I must be missing something. I see lots of examples using RTFEditorKit and filling into the JTextPane but not when its instantiated as a class.
public class RichTextEditor extends TextEditorPane {
private final String extension = ".rtf";
private final String filetype = "text/richtext";
public RichTextEditor() {
// super( null, "", "Untitled", null );
super();
// this.setContentType( "text/richtext" );
}
/**
* Constructor for tabs with content.
*
* #param stream
* #param path
* #param fileName
* #param color
*/
public RichTextEditor( FileInputStream stream, String path, String fileName, Color color, boolean saveEligible ) {
super( path, fileName, color, saveEligible );
super.getScrollableTracksViewportWidth();
//RTFEditorKit rtf = new RTFEditorKit();
//this.setEditorKit( rtf );
setEditor();
this.read(stream, this.getDocument(), 0);
//this.read( stream, "RTFEditorKit" );
this.getDocument().putProperty( "file name", fileName );
}
private void setEditor() {
this.setEditorKit( new RTFEditorKit() );
}
the line:
this.read(stream, this.getDocument(), 0);
tells me
The method read(InputStream, Document) in the type JEditorPane is not applicable for the arguments (FileInputStream, Document, int)
To be able to access your editor kit, you should keep a reference to it. In fact, your setEditor() method's name is setXXX so this should be a setter (in fact, I'm not convinced that you need to set it more than once, so it may be that this method should not exist at all). Define a field:
private RTFEditorKit kit = new RTFEditorKit();
Then in the constructor,
setEditorKit( kit );
kit.read(...);
If you insist on keeping the method, its code should be
kit = new RTFEditorKit();
setEditorKit( kit );
And if you use this from the constructor, remember to set kit to void initially so as not to create an extra object that will be immediately discarded.
I've been looking for a java implementation for loading an RTF document into a JTextPane. Besides this thread, I couldn't find anything else. Thus, I'll post here my solution in case this helps other developers:
private static final RTFEditorKit RTF_KIT = new RTFEditorKit();
(...)
_txtHelp.setContentType("text/rtf");
final InputStream inputStream = new FileInputStream(_helpFile);
final DefaultStyledDocument styledDocument = new DefaultStyledDocument(new StyleContext());
RTF_KIT.read(inputStream, styledDocument, 0);
_txtHelp.setDocument(styledDocument);
Related
I'm working on a code which suppose to take a data to insert into a form and just fill the form with that data.
I'm trying to create a simple pdf multi-page document with the given data in it.
My problem is that my code works partially. I could run the code and generate a multi-page document 6 times in a row, but on the 7th attempt I would get an error like this:
java.io.IOException: COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?
at org.apache.pdfbox.cos.COSStream.checkClosed(COSStream.java:77)
at org.apache.pdfbox.cos.COSStream.createOutputStream(COSStream.java:198)
at org.apache.pdfbox.cos.COSStream.createOutputStream(COSStream.java:186)
at org.apache.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.writeToStream(AppearanceGeneratorHelper.java:641)
at org.apache.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.setAppearanceContent(AppearanceGeneratorHelper.java:303)
at org.apache.pdfbox.pdmodel.interactive.form.AppearanceGeneratorHelper.setAppearanceValue(AppearanceGeneratorHelper.java:170)
at org.apache.pdfbox.pdmodel.interactive.form.PDTextField.constructAppearances(PDTextField.java:263)
at org.apache.pdfbox.pdmodel.interactive.form.PDTerminalField.applyChange(PDTerminalField.java:228)
at org.apache.pdfbox.pdmodel.interactive.form.PDTextField.setValue(PDTextField.java:218)
at app.components.FieldPopulator.insertData(FieldPopulator.java:153)
at app.components.FieldPopulator.populateGoodsFields(FieldPopulator.java:69)
at app.Main.populateData(Main.java:55)
at app.Main.main(Main.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:143)
Error: COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?Document has been createdjava.io.IOException: COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?
at org.apache.pdfbox.cos.COSStream.checkClosed(COSStream.java:77)
at org.apache.pdfbox.cos.COSStream.createRawInputStream(COSStream.java:125)
at org.apache.pdfbox.pdfwriter.COSWriter.visitFromStream(COSWriter.java:1200)
at org.apache.pdfbox.cos.COSStream.accept(COSStream.java:383)
at org.apache.pdfbox.cos.COSObject.accept(COSObject.java:158)
at org.apache.pdfbox.pdfwriter.COSWriter.doWriteObject(COSWriter.java:522)
at org.apache.pdfbox.pdfwriter.COSWriter.doWriteObjects(COSWriter.java:460)
at org.apache.pdfbox.pdfwriter.COSWriter.doWriteBody(COSWriter.java:444)
at org.apache.pdfbox.pdfwriter.COSWriter.visitFromDocument(COSWriter.java:1096)
at org.apache.pdfbox.cos.COSDocument.accept(COSDocument.java:419)
at org.apache.pdfbox.pdfwriter.COSWriter.write(COSWriter.java:1367)
at org.apache.pdfbox.pdfwriter.COSWriter.write(COSWriter.java:1254)
at org.apache.pdfbox.pdmodel.PDDocument.save(PDDocument.java:1232)
at app.Main.saveDocument(Main.java:62)
at app.Main.main(Main.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:143)
I would like to know why is this error keeps coming, or how could it be that the code works sometimes and sometimes it doesn't.
Here is the main class(I removed irrelevent parts of the code):
package app;
import app.components.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by David on 11/01/2017.
*/
public class Main {
private static FormMetaHolder metaHolder = new FormMetaHolder();
private static HashMap<String, Object> properties = new HashMap<>();
private static List<GoodObject> objects = new ArrayList();
private static PDDocument document = new PDDocument();
public static void main(String[] args) throws IOException {
initiateData(); // This method generates sample data. I removed it for simplicity
initiatePdf();
populateData();
saveDocument();
System.out.print("Document has been created");
}
public static void initiatePdf() {
DocumentBuilder builder = new DocumentBuilder();
builder.setObjectsData(objects);
document = builder.build();
}
public static void populateData() throws IOException {
FieldPopulator populator = new FieldPopulator(document.getDocumentCatalog().getAcroForm(), metaHolder);
populator.numberPages();
populator.populateStaticFields(properties);
populator.populateGoodsFields(objects);
}
public static void saveDocument() {
try {
FileOutputStream out = new FileOutputStream(Constants.Paths.RESULT_FILE);
document.save(out);
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is the build() method from DocumentBuilder class. This is the
which generates an empty, ready to be populated document based on how much data need to be inserted:
public PDDocument build() {
PDDocument document = new PDDocument();
try {
int numPages = evaulator.getNumOfPages(objectsToInsert);
// A FieldRenamer for renaming the DG fields sequentially
FieldRenamer renamer = new FieldRenamer();
PDResources res = new PDResources();
// First one here is a list of the unique fields of the document
List<PDField> parentFields = new ArrayList<>();
for (int i = 1; i <= numPages; i++) {
try {
InputStream stream = Main.class.getClassLoader().getResourceAsStream(Constants.Paths.EMPTY_DOC);
templateDoc = new PDDocument().load(stream);
PDDocumentCatalog catalog = templateDoc.getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
if (i == 1)
res = acroForm.getDefaultResources();
// Renaming the PDFields
renamer.setAcroForm(acroForm);
renamer.renameFields(i * 10 + 1 - 10);
PDPage page = catalog.getPages().get(0);
// Iterating over the acro form to find new fields that are not
// In the main collection of fields - the parentFields object
// If a field is already inside the parentFields list, add new
// PDAnnotationWidget to that field, for visual representation
// In the new page
List<PDAnnotation> widgets = new ArrayList<>();
for (PDField field : acroForm.getFields()) {
boolean flag = true;
for (PDField parentField : parentFields) {
String currentFieldName = field.getFullyQualifiedName();
String parentFieldName = parentField.getFullyQualifiedName();
if (currentFieldName.equals(parentFieldName)) {
flag = false;
PDAnnotationWidget existWidget = parentField.getWidgets().get(0);
PDAnnotationWidget widget = new PDAnnotationWidget();
widget.setPage(page);
widget.getCOSObject().setItem(COSName.PARENT, parentField);
widget.setRectangle(existWidget.getRectangle());
parentField.getWidgets().add(widget);
widgets.add(widget);
page.getAnnotations().add(widget);
break;
}
}
if (flag) {
parentFields.add(field);
}
}
document.addPage(page);
stream.close();
} catch (IOException e) {
e.printStackTrace();
System.out.print("Error: could not load the template file");
}
}
PDAcroForm acroForm = new PDAcroForm(document);
acroForm.setFields(parentFields);
acroForm.setDefaultResources(res);
document.getDocumentCatalog().setAcroForm(acroForm);
} catch (NullPointerException e) {
e.printStackTrace();
System.out.print("Error: no data has been set to insert");
}
return document;
}
Now, I think the problem lies with the way I'm dealing with the PDFields and their annotations inside the build() method, but I can't pinpoint the source of the problem.
Please help me with this guys, I've been struggling with this for some time and I just want to proceed with my project, knowing that this part of the program works perfectly.
Thanks in advance!
UPDATE:
Ok so the main cause of the problem is in the build() method inside the DocumentBuilder class. I will try to clarify a little bit about my code:
first, I create a new document which is intended to be the result document.
Next, I figure out using my Evalutor class how much pages are needed in order
to populate the data. Inside the Evaluator I perform certain calculations. A little note, I use the FormMetaHolder object which its job is to provide meta data about acro form fields, data such as field font, font size,
field width and field name. The field font variable holds a reference to
the actual PDFont object I took from the form resources.
Next, I loop over the number of pages and for each iteration I do the following:
.1. Create a new PDDocument from the template file and assign it to templateDoc
.2. Get the acro form from that document.
.2.1. If it's the first iteration, assign default
resources of the acro form to the res variable.
.3. Rename identical fields which I want to contain different values. Because the multi line feature in PDFBox is full of bugs, I divided certain fields of the same size into 10 smaller fields. Each small field like this is numbered. For Instance, if the big field is called "UN" then
all the smaller fields will be called UN1, UN2,
UN3...
Now, if I have a lot of data to insert, I want to be able to duplicate the template document with the only exception of renaming those smaller fields appropriatly. For example, if I need 2 pages to store the data that was
provided by the user, I need 20 smaller fields, 10 for each page.
I need all the UNs field to be renamed like this:
UN1 - UN20
.4. After I rename all the smaller fields accordingly, I try to find new annotations for my list of parentFields. The reason I do that is because besides of the "smaller" fields, I also have static fields which don't change
across pages.
.5. After I find all the correct widgets, I add the current page to the result document and close the InputStream which was used to instantiate the templateDoc object.
After the for loop is over, I create a new PDAcroForm object with the result document as the argument. I set its fields to be
parentFields and set the default resources
to be the res object.
Finally, I set the document acro form to be the newly created acro form.
I want to edit jpg files' properties like: comments, title, date taken, camera maker, etc.
I have found libraries to read these data. But I need a free library with examples to edit them.
I'm aware of apache's imaging (sanselan). But I was not able to edit data with it. If you have previously used it yourself, I'd accept that as an answer only if you provide an example code other than the one in their website. Because even when I use their example I was not able to edit any property other than GPS data. After i run the code, file-properties-details still have the same values.
Thanks !
Note: I also tried JHeader (https://sourceforge.net/projects/jheader/) but using it as a process with -cl option still did not changed properties list.
Apache commons Imaging works for me.
I have extended the sample provided here
So obviously my client code looks like this
public static void main(String[] args) throws ImageWriteException, ImageReadException, IOException {
new WriteExifMetadataExample().changeExifMetadata(new File("somefilename.jpg"), new File("result_file.jpg"));
}
and the extended method in WriteExifMetadataExample
public void changeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add a field/tag to the output set.
//
// Note that you should first remove the field/tag if it already
// exists in this directory, or you may end up with duplicate
// tags. See above.
//
// Certain fields/tags are expected in certain Exif directories;
// Others can occur in more than one directory (and often have a
// different meaning in different directories).
//
// TagInfo constants often contain a description of what
// directories are associated with a given tag.
//
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateExifDirectory();
// make sure to remove old value if present (this method will
// not fail if the tag does not exist).
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_APERTURE_VALUE,
new RationalNumber(3, 10));
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateRootDirectory();
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_SOFTWARE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_SOFTWARE,
"SomeKind");
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
Please pay attention only to line where I add additional tag
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateRootDirectory();
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_SOFTWARE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_SOFTWARE,
"SomeKind");
as a result EXIF tag was properly added
To change the comments tag you can do the following
final TiffOutputDirectory exifDirectory = outputSet.getOrCreateRootDirectory();
exifDirectory.removeField(MicrosoftTagConstants.EXIF_TAG_XPCOMMENT);
exifDirectory.add(MicrosoftTagConstants.EXIF_TAG_XPCOMMENT, "SomeKind");
the full list of available constants is in the package:
org.apache.commons.imaging.formats.tiff.constants
Would an example like this work for you?
I'd assume using packages like org.apache.commons.imaging.util.IoUtils and import org.apache.commons.imaging.Imaging would be of great help to you here.
To change the comments tag you can do the following
final TiffOutputDirectory exifDirectory = outputSet.getOrCreateRootDirectory();
exifDirectory.removeField(MicrosoftTagConstants.EXIF_TAG_XPCOMMENT);
exifDirectory.add(MicrosoftTagConstants.EXIF_TAG_XPCOMMENT, "SomeKind");
the full list of available constants is in the package:
org.apache.commons.imaging.formats.tiff.constants
You need to use Microsoft tag constraints to edit tags
I'm using PDFBox to extract information from a pdf, and the information I'm currently trying to find is related to the x-position of the first character in the line. I can't find anything related to how to get that information though. I know pdfbox has a class called TextPosition, but I can't find out how to get a TextPosition object from the PDDocument either. How do I get the location information of a line of text from a pdf?
In general
To extract text (with or without extra information like positions, colors, etc.) using PDFBox, you instantiate a PDFTextStripper or a class derived from it and use it like this:
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
(There are a number of PDFTextStripper attributes allowing you to restrict the pages text is extracted from.)
In the course of the execution of getText the content streams of the pages in question (and those of form xObjects referenced from those pages) are parsed and text drawing commands are processed.
If you want to change the text extraction behavior, you have to change this text drawing command processing which you most often should do by overriding this method:
/**
* Write a Java string to the output stream. The default implementation will ignore the <code>textPositions</code>
* and just calls {#link #writeString(String)}.
*
* #param text The text to write to the stream.
* #param textPositions The TextPositions belonging to the text.
* #throws IOException If there is an error when writing the text.
*/
protected void writeString(String text, List<TextPosition> textPositions) throws IOException
{
writeString(text);
}
If you additionally need to know when a new line starts, you may also want to override
/**
* Write the line separator value to the output stream.
* #throws IOException
* If there is a problem writing out the lineseparator to the document.
*/
protected void writeLineSeparator( ) throws IOException
{
output.write(getLineSeparator());
}
writeString can be overridden to channel the text information into separate members (e.g. if you might want a result in a more structured format than a mere String) or it can be overridden to simply add some extra information into the result String.
writeLineSeparator can be overridden to trigger some specific output between lines.
There are more methods which can be overridden but you are less likely to need them in general.
In the case at hand
I'm using PDFBox to extract information from a pdf, and the information I'm currently trying to find is related to the x-position of the first character in the line.
This can be implemented as follows (simply adding the information at the start of each line):
PDFTextStripper stripper = new PDFTextStripper()
{
#Override
protected void startPage(PDPage page) throws IOException
{
startOfLine = true;
super.startPage(page);
}
#Override
protected void writeLineSeparator() throws IOException
{
startOfLine = true;
super.writeLineSeparator();
}
#Override
protected void writeString(String text, List<TextPosition> textPositions) throws IOException
{
if (startOfLine)
{
TextPosition firstProsition = textPositions.get(0);
writeString(String.format("[%s]", firstProsition.getXDirAdj()));
startOfLine = false;
}
super.writeString(text, textPositions);
}
boolean startOfLine = true;
};
text = stripper.getText(document);
(ExtractText.java method extractLineStart tested by testExtractLineStartFromSampleFile)
I have an existing PDF from which I want to retrieve images
NOTE:
In the Documentation, this is the RESULT variable
public static final String RESULT = "results/part4/chapter15/Img%s.%s";
I am not getting why this image is needed?I just want to extract the images from my PDF file
So Now when I use MyImageRenderListener listener = new MyImageRenderListener(RESULT);
I am getting the error:
results\part4\chapter15\Img16.jpg (The system
cannot find the path specified)
This is the code that I am having.
package part4.chapter15;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
/**
* Extracts images from a PDF file.
*/
public class ExtractImages {
/** The new document to which we've added a border rectangle. */
public static final String RESOURCE = "resources/pdfs/samplefile.pdf";
public static final String RESULT = "results/part4/chapter15/Img%s.%s";
/**
* Parses a PDF and extracts all the images.
* #param src the source PDF
* #param dest the resulting PDF
*/
public void extractImages(String filename)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(filename);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener(RESULT);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
reader.close();
}
/**
* Main method.
* #param args no arguments needed
* #throws DocumentException
* #throws IOException
*/
public static void main(String[] args) throws IOException, DocumentException {
new ExtractImages().extractImages(RESOURCE);
}
}
You have two questions and the answer to the first question is the key to the answer of the second.
Question 1:
You refer to:
public static final String RESULT = "results/part4/chapter15/Img%s.%s";
And you ask: why is this image needed?
That question is wrong, because Img%s.%s is not a filename of an image, it's a pattern of the filename of an image. While parsing, iText will detect images in the PDF. These images are stored in numbered objects (e.g. object 16) and these images can be exported in different formats (e.g. jpg, png,...).
Suppose that an image is stored in object 16 and that this image is a jpg, then the pattern will resolve to Img16.jpg.
Question 2:
Why do I get an error:
results\part4\chapter15\Img16.jpg (The system cannot find the path specified)
In your PDF, there's a jpg stored in object 16. You are asking iText to store that image using this path: results\part4\chapter15\Img16.jpg (as explained in my answer to Question 1). However: you working directory doesn't have the subdirectories results\part4\chapter15\, hence an IOException (or a FileNotFoundException?) is thrown.
What is the general problem?
You have copy/pasted the ExtractImages example I wrote for my book "iText in Action - Second Edition", but:
You didn't read that book, so you have no idea what that code is supposed to do.
You aren't telling the readers on StackOverflow that this example depends on the MyImageRenderer class, which is where all the magic happens.
How can you solve your problem?
Option 1:
Change RESULT like this:
public static final String RESULT = "Img%s.%s";
Now the images will be stored in your working directory.
Option 2:
Adapt the MyImageRenderer class, more specifically this method:
public void renderImage(ImageRenderInfo renderInfo) {
try {
String filename;
FileOutputStream os;
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
filename = String.format(path,
renderInfo.getRef().getNumber(), image.getFileType());
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
iText calls this class whenever an image is encountered. It passed an ImageRenderInfo to this method that contains plenty of information about that image.
In this implementation, we store the image bytes as a file. This is how we create the path to that file:
String.format(path,
renderInfo.getRef().getNumber(), image.getFileType())
As you can see, the pattern stored in RESULT is used in such a way that the first occurrence of %s is replaced with a number and the second occurrence with a file extension.
You could easily adapt this method so that it stores the images as byte[] in a List if that is what you want.
I'm getting a string 'ÐалендаÑÐ' instead of getting 'Календари' in Java code. How can I convert 'ÐалендаÑÐ' to 'Календари'?
I used
String convert =new String(convert.getBytes("iso-8859-1"), "UTF-8")
String convert =new String(convert.getBytes(), "UTF-8")
I believe your code is okay. It appears that your problem is that you need to do a specific character conversion, and maybe your "real" input is not being encoded correctly. To test, I would do a standard step by step CharSet encoding/decoding, to see where things are breaking.
Your encodings look fine, http://docs.oracle.com/javase/1.6/docs/guide/intl/encoding.doc.html
And the following seems to run normally :
//i suspect your problem is here - make sure your encoding the string correctly from the byte/char stream. That is, make sure that you want "iso-8859-1" as your input characters.
Charset charsetE = Charset.forName("iso-8859-1");
CharsetEncoder encoder = charsetE.newEncoder();
//i believe from here to the end will probably stay the same, as per your posted example.
Charset charsetD = Charset.forName("UTF-8");
CharsetDecoder decoder = charsetD.newDecoder();
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(inputString));
CharBuffer cbuf = decoder.decode(bbuf);
final String result = cbuf.toString();
System.out.println(result);
Use the Unicode values instead of string literals. For more information, see:
Russian on-screen keyboard (hover over for Unicode values)
And how about a list of Unicode characters?
Edit -
Note that it's important to use an output font that supports displaying Unicode values (e.g. Arial Unicode MS).
Example -
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
final class RussianDisplayDemo extends JFrame
{
private static final long serialVersionUID = -3843706833781023204L;
/**
* Constructs a frame the is initially invisible to display Russian text
*/
RussianDisplayDemo()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
add(getRussianButton());
setLocationRelativeTo(null);
pack();
}
/**
* Returns a button with Russian text
*
* #return a button with Russian text
*/
private final JButton getRussianButton()
{
final JButton button = new JButton("\u042da\u043d\u044f\u0442\u043e"); // Russian for "Busy"
return button;
}
public static final void main(final String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public final void run()
{
final RussianDisplayDemo demo = new RussianDisplayDemo();
demo.setVisible(true);
}
});
}
}