My problem is that I need to control mobile robot E-puck via Bluetooth in Java, by sending it commands like "D,100,100" to set speed, "E" to get speed, and etc. I have some code:
String command = "D,100,100";
OutputStream mOutputToPort = serialPort.getOutputStream();
mOutputToPort.write(command.getBytes());
So with this method write I can only send byte[] data, but my robot won't understand that.
For example previously I have been using this commands on Matlab like that:
s = serial('COM45');
fopen(s);
fprintf(s,'D,100,100','async');
Or on program Putty type only:
D,100,100 `enter`
Additional info:
I've also figured out, that Matlab has another solution for same thing.
s = serial('COM45');
fopen(s);
data=[typecast(int8('-D'),'int8') typecast(int16(500),'int8') typecast(int16(500),'int8')];
In this case:
data = [ -68 -12 1 -12 1];
fwrite(s,data,'int8','async');
Wouldn't it be the same in Java:
byte data[] = new byte[5];
data[0] = -'D';
data[1] = (byte)(500 & 0xFF);
data[2] = (byte)(500 >> 8);
data[3] = (byte)(500 & 0xFF);
data[4] = (byte)(500>> 8);
And then:
OutputStream mOutputToPort = serialPort.getOutputStream();
mOutputToPort.write(data);
mOutputToPort.flush();
Main details in code comments. Now you can change wheel speed by typing in command window D,1000,-500 and hitting enter.
public class serialRobot {
public static void main(String[] s) {
SerialPort serialPort = null;
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM71");
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Port in use!");
} else {
System.out.println(portIdentifier.getName());
serialPort = (SerialPort) portIdentifier.open(
"ListPortClass", 300);
int b = serialPort.getBaudRate();
System.out.println(Integer.toString(b));
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setInputBufferSize(65536);
serialPort.setOutputBufferSize(4096);
System.out.println("Opened " + portIdentifier.getName());
OutputStream mOutputToPort = serialPort.getOutputStream();
InputStream mInputFromPort = serialPort.getInputStream();
PerpetualThread t = readAndPrint(mInputFromPort);
inputAndSend(mOutputToPort);
t.stopRunning();
mOutputToPort.close();
mInputFromPort.close();
}
} catch (IOException ex) {
System.out.println("IOException : " + ex.getMessage());
} catch (UnsupportedCommOperationException ex) {
System.out.println("UnsupportedCommOperationException : " + ex.getMessage());
} catch (NoSuchPortException ex) {
System.out.println("NoSuchPortException : " + ex.getMessage());
} catch (PortInUseException ex) {
System.out.println("PortInUseException : " + ex.getMessage());
} finally {
if(serialPort != null) {
serialPort.close();
}
}
}
private static PerpetualThread readAndPrint(InputStream in) {
final BufferedInputStream b = new BufferedInputStream(in);
PerpetualThread thread = new PerpetualThread() {
#Override
public void run() {
byte[] data = new byte[16];
int len = 0;
for(;isRunning();) {
try {
len = b.read(data);
} catch (IOException e) {
e.printStackTrace();
}
if(len > 0) {
System.out.print(new String(data, 0, len));
}
}
}
};
thread.start();
return thread;
}
private static void inputAndSend(OutputStream out) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int k = 0;
for(;;) {
String komanda;
try {
komanda = in.readLine();
} catch (IOException e) {
e.printStackTrace();
return;
}
komanda = komanda.trim();
if(komanda.equalsIgnoreCase("end")) return;
byte komandaSiust[] = proces(komanda); //Command we send after first
//connection, it's byte array where 0 member is the letter that describes type of command, next two members
// is about left wheel speed, and the last two - right wheel speed.
try {
if(k == 0){
String siunc = "P,0,0\n"; // This command must be sent first time, when robot is connected, otherwise other commands won't work
ByteBuffer bb = ByteBuffer.wrap(siunc.getBytes("UTF-8"));
bb.order(ByteOrder.LITTLE_ENDIAN);
out.write(bb.array());
out.flush();
}else{
ByteBuffer bb = ByteBuffer.wrap(komandaSiust);
bb.order(ByteOrder.LITTLE_ENDIAN);
out.write(bb.array());
out.flush();
}
k++;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
private static byte[] proces(String tekstas){
tekstas = tekstas.trim();
char[] charArray = tekstas.toCharArray();
byte kodas1[];
int fComa = tekstas.indexOf(',', 1);
int sComa = tekstas.indexOf(',', 2);
int matavimas = charArray.length;
int skir1 = sComa - fComa - 1;
int skir2 = matavimas - sComa -1;
char leftSpeed[] = new char[skir1];
for(int i = 0; i < skir1; i++){
leftSpeed[i] = charArray[fComa + i + 1];
}
char rightSpeed[] = new char[skir2];
for(int i = 0; i < skir2; i++){
rightSpeed[i] = charArray[sComa + i + 1];
}
String right = String.valueOf(rightSpeed);
String left = String.valueOf(leftSpeed);
int val1 = Integer.parseInt(left);
int val2 = Integer.parseInt(right);
kodas1 = new byte[5];
kodas1[0] = (byte)-charArray[0];
kodas1[1] = (byte)(val1 & 0xFF);
kodas1[2] = (byte)(val1 >> 8);
kodas1[3] = (byte)(val2 & 0xFF);
kodas1[4] = (byte)(val2 >> 8);
return kodas1;
}
private static class PerpetualThread extends Thread {
private boolean isRunning = true;
public boolean isRunning() { return isRunning; }
public void stopRunning() {
isRunning = false;
this.interrupt();
}
}
}
According to the documentation, you need to call setSerialPortParams(int baudrate, int dataBits, int stopBits, int parity) on your serial port.
Related
I have the following code in my client class:
private void onCalculateClick() {
try {
DatagramSocket socket = new DatagramSocket(12346);
DatagramPacket datagramPacket;
InetAddress local = InetAddress.getByName("localhost");
byte[] bytes;
bytes = aTf.getText().getBytes();
datagramPacket = new DatagramPacket(bytes, bytes.length, local, 12345);
socket.send(datagramPacket);
bytes = bTf.getText().getBytes();
datagramPacket = new DatagramPacket(bytes, bytes.length, local, 12345);
socket.send(datagramPacket);
bytes = cTf.getText().getBytes();
datagramPacket = new DatagramPacket(bytes, bytes.length, local, 12345);
socket.send(datagramPacket);
datagramPacket = new DatagramPacket(bytes, bytes.length);
socket.receive(datagramPacket);
resultTf.setText(new String(datagramPacket.getData()));
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
As you can see, here I pass the data from JTextFields to the server and waiting for an answer. By default, the data is 2 in ATF, 8 in bTf and 11 in CTF (maybe it would help). And here's the code of my server:
public class UpdServer {
private double sum1 = 0;
private double sum2 = 0;
private byte[] bytes = new byte[100];
private DatagramSocket socket;
private DatagramPacket datagramPacket = new DatagramPacket(bytes, 100);
public static void main(String[] args) {
new UpdServer();
}
private UpdServer() {
try {
socket = new DatagramSocket(12345);
listen();
} catch (SocketException e) {
e.printStackTrace();
}
}
private void listen() {
int a, b, c;
try {
socket.receive(datagramPacket);
String str = new String(datagramPacket.getData());
System.out.println(str);
a = Integer.parseInt(str);
socket.receive(datagramPacket);
str = new String(datagramPacket.getData());
System.out.println(str);
b = Integer.parseInt(str);
socket.receive(datagramPacket);
str = new String(datagramPacket.getData());
System.out.println(str);
c = Integer.parseInt(str);
Thread firstSumThread = new Thread(() -> {
for (int i = a; i < b; i++) {
sum1 += (i - 1) * (i - 1);
}
});
Thread secondSumThread = new Thread(() -> {
for (int i = b; i < c; i++) {
sum2 += (double) 2 * i / (7 * i + 1);
}
});
firstSumThread.start();
secondSumThread.start();
firstSumThread.join();
secondSumThread.join();
sendBack();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void sendBack() {
String str = String.valueOf(sum1 - sum2);
byte[] send = str.getBytes();
try {
datagramPacket = new DatagramPacket(send, send.length, InetAddress.getByName("localhost"), 12346);
socket.send(datagramPacket);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But when I run the server, client, click on the Calculate button, I get the following error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "2 "
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at com.mikhailovskii.lab2.udp.UpdServer.listen(UpdServer.java:37)
at com.mikhailovskii.lab2.udp.UpdServer.<init>(UpdServer.java:25)
at com.mikhailovskii.lab2.udp.UpdServer.main(UpdServer.java:19)
So, as I understand, it happens after converting the first passed String to int, but I cannot understand why. so, what's the matter and how can I solve this problem?
The problem is that your String contains trailing spaces: "2 ". Therefore a NumberFormatException happens when trying to convert it to Integer.
You may add the .trim() function to your Strings so that leading and trailing spaces are eliminated.
String str = new String(datagramPacket.getData());
if (str != null) {
str = str.trim();
}
a = Integer.parseInt(str);
I currently am writing a program which communicates to a server hosted on a separate device via TCP packets. Writing to the server works fine, but I never seem to be able to read the response. I am positive there is a response because when sniffing network packets, I see the incoming packet from the device, though the program never detects it.
public class SocketTest
{
private Socket socket;
private int currentSequence = 0;
public static void main(String[] args)
{
new SocketTest();
}
public SocketTest()
{
try
{
System.out.println("Connecting");
socket = new Socket("192.168.1.8", 8000);
System.out.println("Connected!");
System.out.println("Pinging...");
sendPacket(0, 3, null, 0);
System.out.println("Pinged!");
System.out.println("Reading..");
while (socket.isConnected())
{
byte[] res = new byte[84];
socket.getInputStream().read(res);
System.out.println("Read!");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void sendPacket(int type, int command, int[] args, int length)
{
int t = 0;
currentSequence += 1000;
byte[] resultBuffer = new byte[84];
byte[] payload1 = getBytes(0x12345678);
System.arraycopy(payload1, 0, resultBuffer, t, payload1.length);
t += 4;
byte[] payload2 = getBytes(currentSequence);
System.arraycopy(payload2, 0, resultBuffer, t, payload2.length);
t += 4;
byte[] payload3 = getBytes(type);
System.arraycopy(payload3, 0, resultBuffer, t, payload3.length);
t += 4;
byte[] payload4 = getBytes(command);
System.arraycopy(payload4, 0, resultBuffer, t, payload4.length);
for (int i = 0; i < 16; i++)
{
t += 4;
int arg = 0;
if (args != null)
{
arg = args[i];
}
byte[] payloadArg = getBytes(arg);
System.arraycopy(payloadArg, 0, resultBuffer, t, payloadArg.length);
}
t += 4;
byte[] payload5 = getBytes(length);
System.arraycopy(payload5, 0, resultBuffer, t, payload5.length);
write(resultBuffer, 0, resultBuffer.length);
}
private void write(byte[] buffer, int startOffset, int length)
{
DataOutputStream out;
try
{
out = new DataOutputStream(socket.getOutputStream());
out.write(buffer, startOffset, length);
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private byte[] getBytes(int value)
{
ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
buffer.putInt(value);
return buffer.array();
}
}
I've tried a bunch of different methods of reading.. Multithreading, heartbeat, etc.. But everytime I use InputStream's read() method, it blocks because there is no data to be read, and the socket is definitely open because the result isn't -1.
This is the actual read method i'm using in my program (The above code is an shortened xample)
private int read(byte[] buffer, int offset, int length)
{
int res = 0;
DataInputStream bis;
try
{
bis = new DataInputStream(socket.getInputStream());
if (bis.available() > 0)
{
System.out.println("Waiting bytes: " + bis.available());
System.out.println("buffer = [" + Arrays.toString(buffer) + "], offset = [" + offset + "], length = [" + length + "]");
res = bis.read(buffer, offset, length);
}
else
{
NTR.getLogger().debug("Available: " + bis.available());
}
}
catch (IOException e)
{
e.printStackTrace();
}
return res;
}
Interestingly, the C# version of the code works just fine.
namespace ntrclient
{
public class NtrClient
{
public delegate void LogHandler(string msg);
private readonly object _syncLock = new object();
private uint _currentSeq;
private int _heartbeatSendable;
public string Host;
private string _lastReadMemFileName;
private uint _lastReadMemSeq;
public NetworkStream NetStream;
public Thread PacketRecvThread;
public int Port;
public volatile int progress = -1;
public TcpClient Tcp;
public event LogHandler OnLogArrival;
private int ReadNetworkStream(Stream stream, byte [] buf, int length)
{
var index = 0;
var useProgress = length > 100000;
do
{
if (useProgress)
{
progress = (int) ((double) index / length * 100);
}
var len = stream.Read(buf, index, length - index);
if (len == 0)
{
Console.WriteLine("No data to be read");
return 0;
}
Console.WriteLine("Read " + len + " datas");
index += len;
} while (index < length);
progress = -1;
Console.WriteLine("Length: " + length + ", Buffer: " + buf);
return length;
}
private void PacketRecvThreadStart()
{
var buf = new byte [84];
var args = new uint [16];
var stream = NetStream;
while (true)
{
try
{
var ret = ReadNetworkStream(stream, buf, buf.Length);
if (ret == 0)
{
break;
}
var t = 0;
var magic = BitConverter.ToUInt32(buf, t);
t += 4;
var seq = BitConverter.ToUInt32(buf, t);
t += 4;
var type = BitConverter.ToUInt32(buf, t);
t += 4;
var cmd = BitConverter.ToUInt32(buf, t);
for (var i = 0; i < args.Length; i++)
{
t += 4;
args [i] = BitConverter.ToUInt32(buf, t);
}
t += 4;
var dataLen = BitConverter.ToUInt32(buf, t);
if (cmd != 0)
{
Log($"packet: cmd = {cmd}, dataLen = {dataLen}");
}
if (magic != 0x12345678)
{
Log($"broken protocol: magic = {magic}, seq = {seq}");
break;
}
if (cmd == 0)
{
if (dataLen != 0)
{
var dataBuf = new byte [dataLen];
ReadNetworkStream(stream, dataBuf, dataBuf.Length);
var logMsg = Encoding.UTF8.GetString(dataBuf);
Log(logMsg);
}
lock (_syncLock)
{
_heartbeatSendable = 1;
}
continue;
}
if (dataLen != 0)
{
var dataBuf = new byte [dataLen];
ReadNetworkStream(stream, dataBuf, dataBuf.Length);
HandlePacket(cmd, seq, dataBuf);
}
}
catch (Exception e)
{
Log(e.Message);
break;
}
}
Log("Server disconnected.");
Disconnect(false);
}
public void ConnectToServer()
{
if (Tcp != null)
{
Disconnect();
Log("Disconnected from previous server, connecting to new one");
}
new Thread(() =>
{
//Thread.CurrentThread.IsBackground = true;
Tcp = new TcpClient { NoDelay = true };
Tcp.Connect(Host, Port);
_currentSeq = 0;
NetStream = Tcp.GetStream();
_heartbeatSendable = 1;
PacketRecvThread = new Thread(PacketRecvThreadStart);
PacketRecvThread.Start();
Program.getMain().Connected = true;
Log("Server connected.");
}).Start();
}
public void Disconnect(bool waitPacketThread = true)
{
try
{
Tcp?.Close();
if (waitPacketThread)
{
PacketRecvThread?.Join();
}
// Not connected anymore
Program.getMain().Connected = false;
Log("Server disconnected.");
}
catch (Exception ex)
{
Log(ex.Message);
}
Tcp = null;
}
public void SendPacket(uint type, uint cmd, uint [] args, uint dataLen)
{
var t = 0;
_currentSeq += 1000;
var buf = new byte [84];
BitConverter.GetBytes(0x12345678).CopyTo(buf, t);
t += 4;
BitConverter.GetBytes(_currentSeq).CopyTo(buf, t);
t += 4;
BitConverter.GetBytes(type).CopyTo(buf, t);
t += 4;
BitConverter.GetBytes(cmd).CopyTo(buf, t);
for (var i = 0; i < 16; i++)
{
t += 4;
uint arg = 0;
if (args != null)
{
arg = args [i];
}
BitConverter.GetBytes(arg).CopyTo(buf, t);
}
t += 4;
BitConverter.GetBytes(dataLen).CopyTo(buf, t);
NetStream.Write(buf, 0, buf.Length);
}
public void SendHeartbeatPacket()
{
if (Tcp == null)
return;
lock (_syncLock)
{
if (_heartbeatSendable != 1)
return;
_heartbeatSendable = 0;
SendPacket(0, 0, null, 0);
}
}
}
}
I'm honestly stumped. I noticed that C#'s NetworkStream read and write methods are different from java, but I don't exactly know how different they are, or if it makes any difference.
Thanks in advance!
I have to make an abstaction in my software - replace direct unblockable NIO sockets ( client/server ) to software abstraction.
For example, instead of connecting via tcp client would exec openssl s_client -connect xxx.xxx.xxx.xxx . I have written a little demo, and it even works. Sometimes :(
The first trouble is that Process's streams can't be used with Selector, so I can't replace socketchannel with any other type of channel, so I have to read/write without any chance to avoid blocking.
The second one is that a protocol is a duplex binary file-transfer protocol ( binkp ), so process's buffered streams are unusabe. I've tried to avoid that converting in/out data to base64 and it works, but also sometimes.
I can't understant why it works or not sometimes. I put a piece of test code below. The first word is frame's length, but first bit is ignored. Please, tell me your guesses. Thanks.
public class BufferedSocketBase64 {
static class InToOut implements Runnable {
InputStream is;
OutputStream os;
boolean direction; //
public InToOut(InputStream is, OutputStream os, boolean direction) {
super();
this.is = is;
this.os = os;
this.direction = direction;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getId() + " start "
+ ((direction) ? "encode from to" : "decode from to"));
boolean eof = false;
while (true) {
if (direction) {
// encode to base64 data
try {
int[] head = new int[2];
for (int i = 0; i < 2; i++) {
head[i] = is.read();
}
int len = (head[0] & 0xff << 8 | head[1] & 0xff) & 0x7FFF;
byte[] buf = new byte[len + 2];
buf[0] = (byte) (head[0] & 0xff);
buf[1] = (byte) (head[1] & 0xff);
for (int i = 2; i < len; i++) {
buf[i] = (byte) (is.read() & 0xff);
}
System.out.println(Thread.currentThread()
.getId() + " << " + new String(buf));
if (len > 0) {
String send = Base64Util.encode(buf, len);
send += "\n";
os.write(send.getBytes());
os.flush();
}
} catch (IOException e) {
eof = true;
}
} else { // decode from base64
try {
StringBuilder sb = new StringBuilder(1024);
byte c = 0x0a;
do {
c = (byte) is.read();
if (c >= 0 && c != 0x0a) {
sb.append(new String(new byte[] { c }));
}
} while (c != 0x0a && c >= 0);
if (sb.length() != 0) {
try {
byte[] buf = Base64Util.decode(sb.toString());
System.out.println(Thread.currentThread()
.getId() + " >> " + buf.length);
os.write(buf);
os.flush();
} catch (StringIndexOutOfBoundsException e) {
System.out
.println(Thread.currentThread().getId()
+ " error on " + sb.toString());
}
}
} catch (IOException e) {
eof = true;
}
}
if (eof) {
System.out.println(Thread.currentThread().getId() + " EOF");
break;
}
}
try {
is.close();
os.close();
} catch (IOException e) {
}
}
}
public static void main(String[] args) throws Exception {
Process proc2 = Runtime.getRuntime().exec("nc -l -p 2020");
Process proc1 = Runtime.getRuntime().exec("nc 127.0.0.1 2020");
Socket sock1 = new Socket();
sock1.connect(new InetSocketAddress("127.0.0.1", 24554), 30);
Socket sock2 = new Socket();
sock2.connect(new InetSocketAddress("127.0.0.1", 24557), 30);
new Thread(new InToOut(sock1.getInputStream(), proc1.getOutputStream(),
true)).start();
new Thread(new InToOut(proc1.getInputStream(), sock1.getOutputStream(),
false)).start();
new Thread(new InToOut(sock2.getInputStream(), proc2.getOutputStream(),
true)).start();
new Thread(new InToOut(proc2.getInputStream(), sock2.getOutputStream(),
false)).start();
}
UPDATED:
I've found right way. I uses syncchronized queries for each stream and synchronized threads to fill or erase that queries. All threads mutually blocks themselves. And it works! :)
Sorry for bother.
I've found right way. I uses syncchronized queries for each stream and synchronized threads to fill or erase that queries. All threads mutually blocks themselves. And it works! :) Sorry for bother.
Can anybody see what is wrong with this code. it does not show up progress-bar but uploades all the files.
I did checkout sun tutorial and swingworkers also but i couldn't fix it yet.
private static boolean putFile(String m_sLocalFile, FtpClient m_client) {
boolean success = false;
int BUFFER_SIZE = 10240;
if (m_sLocalFile.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(m_sLocalFile);
int size = (int) f.length();
System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(m_sLocalFile);
//test
InputStream inputStream = new BufferedInputStream(
new ProgressMonitorInputStream(null,"Uploading " + f.getName(),in));
//test
OutputStream out = m_client.put(f.getName());
int counter = 0;
while (true) {
int bytes = inputStream.read(buffer); //in
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
inputStream.close();
success =true;
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
return true;
}
I think your code is fine.
Maybe the task isn't taking long enough for the progress bar to be needed?
Here's a modified version of your code which reads from a local file and writes to another local file.
I have also added a delay to the write so that it gives the progress bar time to kick in.
This works fine on my system with a sample 12MB PDF file, and shows the progress bar.
If you have a smaller file then just increase the sleep from 5 milliseconds to 100 or something - you would need to experiment.
And I didn't even know that the ProgressMonitorInputStream class existed, so I've learnt something myself ;].
/**
* main
*/
public static void main(String[] args) {
try {
System.out.println("start");
final String inf = "d:/testfile.pdf";
final String outf = "d:/testfile.tmp.pdf";
final FileOutputStream out = new FileOutputStream(outf) {
#Override
public void write(byte[] b, int off, int len) throws IOException {
super.write(b, off, len);
try {
// We delay the write by a few millis to give the progress bar time to kick in
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
putFile(inf, out);
System.out.println("end");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static boolean putFile(String m_sLocalFile, OutputStream out /*FtpClient m_client*/) {
boolean success = false;
int BUFFER_SIZE = 10240;
if (m_sLocalFile.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(m_sLocalFile);
int size = (int) f.length();
System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(m_sLocalFile);
//test
InputStream inputStream = new BufferedInputStream(
new ProgressMonitorInputStream(null,"Uploading " + f.getName(),in));
//test
//OutputStream out = m_client.put(f.getName());
int counter = 0;
while (true) {
int bytes = inputStream.read(buffer); //in
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
inputStream.close();
success =true;
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
return true;
}
i convert a mp3 file into byte array and i read from byte array but it shows null pointer exception on line number 15
my code:
public class MainClass {
static byte[] bytesarray = null;
public static void main(String args[]) {
try {
FileInputStream fis = new FileInputStream("D:\\taxi.mp3");
try {
fis.read(bytesarray, 0, 32);
System.out.println(bytesarray.length);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayInputStream in = new ByteArrayInputStream(bytesarray);
for (int i = 0; i < 32; i++) {
int c;
while ((c = in.read()) != -1) {
if (i == 0) {
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
}
}
}
static byte[] bytesarray = new byte[32]; should do the work, you didn't initialize your array...
See the documentation of read.
static byte[] bytesarray = new byte[32];