Read string from USB HID RFID Reader with Java - java

I'm trying to read a String from a via USB connected RFID-Reader. The Reader is recognized correctly inside my appliaction. But I do not know how to read the transferred characters into a String.
If I do not detach the device, the String is printed like by a Keyboard (as you would expect from a HID). What I want is to catch that String inside my Java application only. This is the reason why I detach the USB device.
For example my application prints '"''#$&' to the console (see code below) or something like this
[0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
But what I wanted to read is 05006790.
I think that there is a stupid false in my attempt. I hope that someone can help me to figure out how I have to read the Bytes into a String correctly.
Thank you very much.
CODE FOLLOWS HERE
Context context = new Context();
int result = LibUsb.init(context);
DeviceList list = new DeviceList();
result = LibUsb.getDeviceList(context, list);
for (Device device: list)
{
int address = LibUsb.getDeviceAddress(device);
int busNumber = LibUsb.getBusNumber(device);
DeviceDescriptor descriptor = new DeviceDescriptor();
DeviceHandle handle = new DeviceHandle();
int resultOpen = LibUsb.open(device, handle);
// if (resultOpen < 0) // handle = null;
int resultDescriptor = LibUsb.getDeviceDescriptor(device, descriptor);
// if (resultDescriptor< 0) // handle = null;
if(descriptor.idVendor() == 0x8ff && descriptor.idProduct() == 0x0009)
{
System.out.println("found");
LibUsb.detachKernelDriver(handle, 0);
}
}
UsbServices services = UsbHostManager.getUsbServices();
UsbDevice deviceHigh = findDevice(services.getRootUsbHub(), (short) 0x8ff, (short) 0x0009);
if(deviceHigh != null)
{
System.out.println("found high");
UsbConfiguration configuration = deviceHigh.getActiveUsbConfiguration();
UsbInterface iface = configuration.getUsbInterface((byte) 0x00);
iface.claim();
UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x81);
UsbPipe pipe = endpoint.getUsbPipe();
pipe.open();
byte[] buffer = new byte[128];
int rx = 0;
rx = pipe.syncSubmit(buffer);
System.out.printf("%d bytes received\n", rx);
System.out.println(Arrays.toString(buffer));
iface.release();
}

Related

Dijkstra's Algorithm and trouble with A* algorithm

So I have been searching these two algorithms on the Internet and was able to, after days of working on it, get Dijkstra's Algorithm working. From what I have read the two Algorithms are not that different. So I am going to post what I did for Dijkstra's and I was hoping that you can show me or point me into the direction on how to modify it to the A* algorithm.
public Integer processGraph(int graph[][], int algorithm, int s, int d) {
if(algorithm == 1) {
// shortestDist[index] will hold the distance from s to the index
int shortestDist[] = new int[graph.length];
// added[i] is true if vertex index is included / the shortest distance from the source to the index is finalized
boolean added[] = new boolean[graph.length];
// establish all distances as Integer.Max_Value and added[] as false
for (int vertexIndex = 0; vertexIndex < graph.length; vertexIndex++) {
shortestDist[vertexIndex] = Integer.MAX_VALUE;
added[vertexIndex] = false;
}
// Distance of the source from itself is always 0
shortestDist[s] = 0;
// Parent array to store shortest the shortest path -- example: [num, num, num]
int[] parents = new int[graph.length];
// Find shortest path for all vertices
for (int i = 1; i < graph.length; i++) {
// Pick the minimum distance vertex
// from the set of vertices not yet
// processed. nearestVertex is
// always equal to the source in
// first iteration.
int u = minDistance(shortestDist, added);
added[u] = true;
for (int vertexIndex = 0; vertexIndex < graph.length; vertexIndex++) {
if (!added[vertexIndex] && graph[u][vertexIndex] != 0 && shortestDist[u] != Integer.MAX_VALUE && shortestDist[u] + graph[u][vertexIndex] < shortestDist[vertexIndex]) {
shortestDist[vertexIndex] = shortestDist[u] + graph[u][vertexIndex];
parents[vertexIndex] = u;
}
}
}
if(shortestDist[d] == Integer.MAX_VALUE) {
System.out.println(" ");
System.out.println("ERROR MESSAGE -- No path present from " + s + " to " + d);
System.out.println("ERROR MESSAGE --no path present from " + s + " to " + d);
System.out.println(" ");
return null;
}
//pathPrint(s, shortestDist, d); this only works for the first test
return shortestDist[d];
} // end algorithm 1
TO add more context to this, I have a driver class in which with several graphs upon which this finds the shortest path.
Example of graph[][]:
int regValid[][] = {{0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,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, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0}};
Again, how can I modify what I have to work with the A* algorithm instead of Dijkstras. Thank you and hopefully this makes sense.
You have full information about all nodes, edges and destination node, so Dijkstra is the best solution for your problem. A* would be useful if you hadn't known complete graph (most often for huge node space) and were forced to prioritize decisions according to some heuristics.
If you really want to simulate A* on your graph, you have to think out some artificial criterion (heuristics) which describes the estimated distance between given node and target node (in other words, pretend you don't know the path). Since your data set doesn't contain such additional information (and thinking out any satisfying admissibility condition is not trivial), your question doesn't make much sense to me.

how to convert string to collection

I have a string in the below format.
[[115, 1, 0123490, 63824005632, 0036760004, , 01, N, 78, , 7481067028,
122016, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, RXRELIEF CARD,
MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG], [115, 1, 0123490,
63824005632, 0038380001, ,
01, N, 78, , 7481067028, 122016, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA,
OH, 45805, EM, APEX AFFINITY DISCOUNT CARD, MUCINEX DM 20 0056-32 TAB SA
12HR 600-30MG]]
I want to store in collection with each
[115, 1, 0123490, 63824005632, 0038380001, , 01, N, 78, , 7481067028,
122016, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, APEX AFFINITY
DISCOUNT CARD, MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG]
[115, 1, 0123490, 63824005632, 0036760004, , 01, N, 78, , 7481067028,
122016, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, RXRELIEF CARD,
MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG]
How can I split or store in collection?
This should work as long the character ] does not appear as part of a value inside an entry:
public static void main(String[] args) {
String clob = "[[115, 1, 0123490, 63824005632, 0036760004, , 01, N, 78, , 7481067028, 122016, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, RXRELIEF CARD, MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG], [115, 1, 0123490, 63824005632, 0038380001, , 01, N, 78, , 7481067028, 122016, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TABORA, EMMANUEL, J, 4732 WENATCHIE TRL, LIMA, OH, 45805, EM, APEX AFFINITY DISCOUNT CARD, MUCINEX DM 20 0056-32 TAB SA 12HR 600-30MG]]";
List<String> entries = new ArrayList<>();
int start = 1;
while (true) {
start = clob.indexOf("[", start);
int end = clob.indexOf("]", start);
if (start != -1 && end != -1) {
entries.add(clob.substring(start, end + 1));
start = end + 1;
} else {
break;
}
}
}
If you know the escape sequence for characters inside your entries (e.g. \]) you have to check if the found end index represents that escape sequence and if, read again, starting from the end index.
There are many ways to do it. Here’s my suggestion:
public static List<List<String>> stringTo2DList(String input) {
if (input.equals("[]")) {
return Collections.emptyList();
}
if (! input.startsWith("[[")) {
throw new IllegalArgumentException("Not a list of lists");
}
if (! input.endsWith("]]")) {
throw new IllegalArgumentException("Not a list of lists");
}
List<List<String>> result = new ArrayList<>();
String[] innerLists = input.substring(2, input.length() - 2).split("\\], \\[");
for (String innerList : innerLists) {
// check for empty inner list
if (innerList.isEmpty()) {
result.add(Collections.emptyList());
} else {
result.add(Arrays.asList(innerList.split(", ")));
}
}
return result;
}
Should your string contain [], I am interpreting it as an empty list even though it might be a list of one element, the empty string. If you prefer the latter, just skip the check for the empty list in for loop.

Colision detecting in java(Tiled map)

Here i have a code with a picture moving around the map.
How to make this picture colide when interacte with map tiles ? I'm a beginer at java so i have no ideas. Any Help or advise is very welcome.
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.Timer;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import org.omg.CORBA.portable.InputStream;
import java.io.Reader;
public class NewTest extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private Image TestImage;
private BufferedImage bf;
private BufferedImage bufferedImage;
private int cordX = 100;
private int cordY = 100;
public int mapy=25;
public int mapx=mapy;
public int size= 20;
private boolean down, up, left, right;
private Image wall = Toolkit.getDefaultTo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5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 13}};
public NewTest() throws IOException {
setTitle("Testing....");
setSize(mapy*size+50,mapx*size+50);
imageLoader();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void imageLoader() throws IOException {
TestImage = Toolkit.getDefaultToolkit().getImage("image/Koala.jpg");
addKeyListener(this);
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
bf = new BufferedImage( this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB);
try{
animation(bf.getGraphics());
g.drawImage(bf,0,0,null);
}catch(Exception ex){
}
}
public void animation(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
for (int y = 0; y <= mapy; y++){
for (int x = 0; x <= mapx; x++){
int L = x * size;
int U = y * size;
int R = size;
int D = size;
/// g2d.rotate(Math.toRadians(-90));
if (map[y][x] == 1){
//no black wall
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
}else if (map[y][x] == 2){
//on left
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L-size/2 +2, U, 8, size);
}else if (map[y][x] == 3){
//on right
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L+size, U, 8, size);
}else if (map[y][x] == 4){
//on top
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U-size/2 + 2, size, 8);
}else if (map[y][x] == 5){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}else if (map[y][x] == 10){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U-size/2 + 2, size, 8);
g2d.fillRect(L-size/2 +2, U, 8, size );
}else if (map[y][x] == 11){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}else if (map[y][x] == 12){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}else if (map[y][x] == 13){
//on bottom
g2d.setColor(Color.green);
g2d.fillRect(L, U, R, D);
g2d.setColor(Color.black);
g2d.fillRect(L, U+size, size, 8);
}
}
}
g.drawImage(TestImage, cordX, cordY,20 , 20, this);
}
public static void main(String[] args) {
try {
new NewTest();
} catch (IOException e) {
e.printStackTrace();
}
}
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
case KeyEvent.VK_UP:
up = true;
break;
}
updateState();
}
public void keyReleased(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_DOWN:
down = false;
break;
case KeyEvent.VK_UP:
up = false;
break;
}
updateState();
}
protected void updateState() {
if (right) {
cordX += 5;
} else if (left) {
cordX -= 5;
}
if (down) {
cordY += 5;
} else if (up) {
cordY -= 3;
}
if (down && up) {
cordY += 0;
cordX += 0;
}
if (right && left) {
cordX += 0;
cordY += 0;
}
System.out.printf("X:");System.out.println(cordX);
System.out.printf("Y:");System.out.println(cordY);
repaint();
}
public void keyTyped(KeyEvent ke) {
}
}
Thank you for help!
Good approach is to seperate visual and reality model. It means deep in the program, you have your "physics rules" and all objects and based on that model, you draw it.
You can start with creating class like this
public class ObjectInMyGame{
private int posx;
private int posy;
private int width;
private int height;
private Image image;
private int movingX;
private int movingY;
//Note that it is good to use Point or something like that, instead of posx, posy.
}
Then it is good to have some kind of "game controller", which is running your whole world.
public class GameController{
List<ObjectInMyGame> objects;
public updateGame(){
for (ObjectInMyGame object : objects){
object.doSomething(); //sometimes it is good idea to let objects itself do something
}
}
}
So for example, when you move object, you can check, if he collide or not and then decide what to do.

Eliminate default zeros while creating string from byte array

I am getting bytes from IOStream and converting it to string. From that string i am extracting a sequence using substring api.
Size of ByteArray is 128 bytes. If the stream contains only 10 bytes and remaining are filled with zero[initially filled]. I am converting the byte array to string by passing to a string constructor new String(byte[]) and checking the length. The length is 128. Why it is showing 128? Actually it should show for 10 byte character length.
How to eliminate the zero while converting to string. Is there any api's to eliminate the default zeros in byte array. It's creating problem while creating a substring from the constructed string.
byte[] b = { 99, 116, 101, 100, 46, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0}
System.out.println("byte length = " + b.length);
String str;
try {
str = new String(b, "UTF-8");
System.out.println("String length = " + str.length());
System.out.println(str);
System.out.println(" ## substring = " + str.substring(0));
System.out.println(" substring length = "
+ str.substring(0).length());
System.out.println("Done......");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}0, 0, 0 };
To create a String from part of a byte array, use the constructor String(byte[] bytes, int offset, int length, String charsetName). Example:
// uses the first 10 bytes of b
str = new String(b, 0, 10, "UTF-8");
Also, if you're compiling for Java 7 you might as well use StandardCharsets (from the java.nio.charset package), and avoid having to handle UnsupportedEncodingException. Example:
str = new String(b, 0, 10, StandardCharsets.UTF_8);
When you read from an InputStream, it will tell you how many bytes were read. The length of the byte[] itself is mostly irrelevant (other than defining the max number of bytes which could be read in a single call). There should be no need to later go examine the byte[] to try and determine how much of the data is relevant. Pay attention to the return value from read and use that when creating a String.
Additionally, if all of your data is text, consider using an InputStreamReader, perhaps in combination with a BufferedReader.
First an explanation.
Not every byte sequence is valid UTF-8. A binary byte 0 (0x00) is valid, and does not terminate a String as in C.
In fact a terminating \0 was later deplored by either C's Kernighan or Ritchie, as being suboptimal.
To prevent problems, not only Unicode code points above U+007F (0x7f) are multi-byte encoded (whith high bits of bytes set), but also U+0000 in Java's UTF-8, DataOutputSream.
byte[] bytes = get UTF-8 bytes from string
Now bytes could have a multi-byte sequence for the code point 0.
So you might either clean up the bytes, a small loop, or clean up the string:
str = str.replace("\u0000", ""); // All bytes 0
str = str.replaceFirst("\u0000+$", ""); // Only trailing bytes 0, regex
Your code would be like this
byte[] b = { 99, 116, 101, 100, 46, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0};
int nonZeroPos=0;
for (int i = b.length-1; i >0; i--) {
if(b[i]!=0){
nonZeroPos=i;
break;
}
}
System.out.println("byte length = " + b.length);
String str;
try {
str = new String(b, 0, nonZeroPos, "UTF-8");
System.out.println("String length = " + str.length());
System.out.println(str);
System.out.println(" ## substring = " + str.substring(0));
System.out.println(" substring length = "
+ str.substring(0).length());
System.out.println("Done......");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You also could have it done this way -
String zerostring = new String(new byte[]{0});
str=new String(b).replace(zerostring , "");
System.out.println(str);
But disadvantage of this is it will replace 0s coming in the word.

use fileReader in java to read one character at a time

As a part of a school exercise, I am trying to read characters from a text file and count the frequency of the characters appeared the text file. I stored the frequency in an array, where the index is the ASCII code of the char, and the number in the array is the frequency.
int c;
FileReader fr = new FileReader (inputFile);
int [] freq = new int [200];
while ( (c= fr.read())!= -1){
int index = c;
freq [index]= freq [index]+1;
}
PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
for (int i =0; i<frequency.length; i++) {
if(frequency[i]!=0){
pw.println( ((char)i) + " " +frequency[i]);
Somehow this method only works with text files with a single line, like "abcdefgh". It doesn't work with files with multiple lines, like "ab /newline cde /newline..." For this type of file, it will generate a blank line and some numbers on top of the result when I print out the array. I really couldn't figure out why.
It looks fine to me.
import java.io.FileReader;
import java.util.Arrays;
public class Foo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("/tmp/a");
int[] freq = new int[200];
int c;
while ((c = fr.read()) != -1) {
freq[c] = freq[c] + 1;
}
System.out.println(Arrays.toString(freq));
}
}
Example contents of /tmp/a:
abc
def
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
edit - In response to the revised question:
The output is
2
a 1
b 1
c 1
d 1
e 1
f 1
The file has two line breaks, so the program is writing a line break, and then "2".
I'm guessing you want to convert the characters to something like their Java escape sequences. Here's a solution using Apache commons-lang:
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Foo {
public static void main(String[] args) throws Exception {
write(read());
}
static int[] read() throws IOException {
FileReader fr = new FileReader("/tmp/a");
int[] freq = new int[200];
int c;
while ((c = fr.read()) != -1) {
freq[c] = freq[c] + 1;
}
return freq;
}
static void write(int[] freq) throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter("/tmp/b"))) {
for (int i = 0; i < freq.length; i++) {
if (freq[i] != 0) {
char c = (char) i;
String s = StringEscapeUtils.escapeJava("" + c);
pw.println(s + " " + freq[i]);
}
}
}
}
}
Output:
\n 2
a 1
b 1
c 1
d 1
e 1
f 1

Categories