How to convert a String to an InputStream in Kotlin? - arrays

I have a string:
var myString:String = "My String"
How can I convert it to an InputStream in Kotlin?

Kotlin has an extension for String to convert directly.
val inputStream: InputStream = myString.byteInputStream()
The argument on byteInputStream is defaulted to charset: Charset = Charsets.UTF_8.
You can look at the extension by writing it and then cmd+click on it or in the package kotlin.io file IOStream.kt
Relying on the Java version is not wrong, but rather using a more kotlin idiomatic way when possible

val myString = "text"
val targetStream: InputStream = ByteArrayInputStream(initialString.toByteArray())
Pst.
If you copy some java code, for example:
String myString = "text";
InputStream targetStream = new ByteArrayInputStream(myString.getBytes());
Android Studio will popup "Clipboard content seems to be Java code. Do you want to convert it to Kotlin?

Related

How to convert image file to base64 String in flutter?

I am try to convert a image file in flutter:
File _img=new File('/data/user/0/com.example.test3/app_flutter/2020-10-29T17:18:56.210347.png');
List<int> imageBytes = _img.readAsBytesSync();
String imageB64 = base64Encode(imageBytes);
print(imageB64);
But it look like is a wrong base64 String and I cannot decode to image on convert website:
https://codebeautify.org/base64-to-image-converter
iVBORw0KGgoAAAANSUhEUgAAAhwAAALECAYAAABDk+k+AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAACAASURBVHic7d1ngFx1ucDhd9N77z0hbdMhCSAJVZoURS4C0psColcxFBXFKypKUywUQYp0EdtVQHpHTQLpZZOQnpDee9v7QeUSksxsyP7Ptuf5tnPeybwfCPvLmTNnIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgNJRUFYvXFxcXFxWrw0AVVVBQUGZ/O6vVhYvCgBULYIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhM
Is the dart base64 format is different to another?
Thanks.
You have to convert your bytes into an Uint8List object not a List<int>:
File _img = File(
'/data/user/0/com.example.test3/app_flutter/2020-10-29T17:18:56.210347.png');
final bytes = Uint8List.fromList(_img.readAsBytesSync());
final imgBase64 = base64Encode(bytes);
print(imgBase64);
I find that this case by the 'print' function cannot display fully base64 code.
If want to verify it, need to export to text file:
_write(String text) async {
final File file = File('/storage/emulated/0/xxx/my_file.txt');
await file.writeAsString(text);
print(file);
}

DigestUtils.md5Hex() generates wrong hash value when passing String object

I'm trying to generate a md5 hash in Kotlin using the DigestUtils class from the org.apache.commons.codec. Here's the test code
#Test
fun md5Test(){
val userPassword: String = "123"
val md5Hash: String = "202cb962ac59075b964b07152d234b70"
assertEquals(md5Hash, DigestUtils.md5Hex(userPassword))
}
The problem is that when I run this test it fails and says that the generated md5 hash is 28c1a138574866e9c2e5a19dca9234ce
But... when I pass the String value instead of the object
assertEquals(md5Hash, DigestUtils.md5Hex("123"))
The test passes without errors
Why this is happening?
Here is a complete solution to get MD5 base64 hash:
fun getMd5Base64(encTarget: ByteArray): String? {
val mdEnc: MessageDigest?
try {
mdEnc = MessageDigest.getInstance("MD5")
// Encryption algorithmy
val md5Base16 = BigInteger(1, mdEnc.digest(encTarget)) // calculate md5 hash
return Base64.encodeToString(md5Base16.toByteArray(), 16).trim() // convert from base16 to base64 and remove the new line character
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
return null
}
}
This is the most simple and complete solution in kotlin:
val hashedStr = String.format("%032x", BigInteger(1, MessageDigest.getInstance("MD5").digest("your string value".toByteArray(Charsets.UTF_8))))

How to decode DUKPT CBC mode in Java?

I can't decode the DUKPT swipe Data, I'm trying using differers examples but the credit card information is encoded yet.
I had a headache trying of decoding the swipe information:
This example can help you to do it:
To Download the Java Example here: https://github.com/ricardojava/mobile/tree/master/TEST_GATE2all/src/com/bbpos
To Modify the file: https://github.com/ricardojava/mobile/blob/master/TEST_GATE2all/src/com/bbpos/SimpleMain.java
String bdk = "0123456789ABCDEFFEDCBA9876543210";
String ksn = "00000232100117e00027";
String tk1 = "de8bfe769dca885cf3cc312135fe2cccfacf176235f4bdee773d1865334315ed2aefcab613f1884b5d63051703d5a0e2bd5d1988eeabe641bd5d1988eeabe641";
String key = DUKPTServer.GetDataKey(ksn, bdk);
String decryptedTLV = TripleDES.decrypt_CBC(tk1, key);
byte[] s = DatatypeConverter.parseHexBinary(decryptedTLV);
System.out.println(new String(s));
}
I hope it can help you!........

Input Mismatch scanner.next(string pattern) from file

I'm having a problem while using a
Scanner file = new Scanner(filePath);
my file is organised as so
Question x.y
Answer1
Answer2
Answer3
Answer4
Hint: Hint to Question x.y Level z Genere t
I'm quite new to java and in all of this project I've used
.next(string pattern)
to return a string that includes the parrtern and arrives to the end of the line but i continue to get mismatch exceptions.. i don't really get what
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
defines as token and for this reason i don't know how to handle it..
my code is
public Question getQuestion(String filePath)
{
ArrayList questions = new ArrayList();
Scanner file = new Scanner(filePath);
String questionInFile = "Question";
while(file.hasNextLine())
questions.add(questionInFile+file.next(questionInFile));
Random rg = new Random();
String Q = (String)questions.get(rg.nextInt(10)+1);
file.close();
ArrayList<String> answer=getAnswers(filePath, Q);
String correctAnswer=answer.get(0);
return new Question(Q, answer, correctAnswer);
}
try adding
File filePath = new File(".txt");
before Scanner file

How to split a File Source into Strings or Words

I have a file with content like this:
"Some","Words","separated","by","comma","and","quoted","with","double","quotes"
The File is to large to read it into just on String.
What is the simplest way to split it into a Traversable of Strings, with each element being a word?
If it matters: While the content of the file won't fit in a single String the resulting Traversable might be a List without a problem.
Here is an adaptation of your own solution, using JavaConversions to manipulate the Java iterator as a Scala one.
import java.util.Scanner
import java.io.File
import scala.collection.JavaConversions._
val scanner = new Scanner(new File("...")).useDelimiter(",")
scanner.map(_.trim).map(quoted => quoted.substring(1, quoted.length - 1))
This gives you an iterator. You can always convert it to a list using e.g. .toList.
Here is a version using stringLit and repsep from Scala parser combinators. I won't vouch for its efficiency, though.
import scala.util.parsing.combinator.syntactical.StdTokenParsers
import scala.util.parsing.combinator.lexical.StdLexical
import scala.util.parsing.input.StreamReader
import java.io.FileReader
object P extends StdTokenParsers {
type Tokens = StdLexical
val lexical = new StdLexical
lexical.delimiters += ","
def words : Parser[List[String]] = repsep(stringLit, ",")
def getWords(fileName : String) : List[String] = {
val scanner = new lexical.Scanner(StreamReader(new FileReader(fileName)))
// better error handling wouldn't hurt.
words(scanner).get
}
}
I did it using the java.util.Scanner while it does work, I'd appreciate a more scalaesc version.
val scanner = new Scanner(new File("""bigFile.txt""")).useDelimiter(",")
var wordList: Vector[String] = Vector()
while (scanner.hasNext()) {
val quoted = scanner.next()
val word = quoted.replace("\"", "")
wordList = wordList :+ word
}

Resources