how to preserve newline character in a string after converting to bytes? - java

String str[] = {"1000458551||A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F||1||7707||0||"
+ "0||1002||1373569142000||HTC One||val||4.1.2||0||1.01.20130206.15441^^1000458551||A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F||"
+ "1||7707||0||0||1002||1373569142000||HTC One||val||4.1.2||0||1.01.20130206.15441","1000458551||A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F||1||7707||0||"
+ "0||1002||1373569142000||HTC One||val||4.1.2||0||1.01.20130206.15441^^1000458551||A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F||"
+ "1||7707||0||0||1002||1373569142000||HTC One||val||4.1.2||0||1.01.20130206.15441"};
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for(String p:str){
String Recordstore[] = p.split("\\^\\^");
long len = Recordstore.length;
long counter = 0;
StringBuffer finalRecord = new StringBuffer();
for (String rec : Recordstore) {
rec = rec.replaceAll("\\|\\|", "|");
if (counter != len - 1)
finalRecord.append(rec).append(System.lineSeparator());
else
finalRecord.append(rec);
counter++;
}
baos.write(finalRecord.toString().getBytes());
}
ByteArrayInputStream object = new ByteArrayInputStream(
baos.toByteArray());
String pr="";
for(int y = 0 ; y < 1; y++ ) {
while(( c= object.read())!= -1) {
pr+=(char)c;
}
System.out.println(pr);
object.reset();
}
After converting the string to bytes and rechecking the bytes, I see that the new line character is lost and the string are combined in a single line.
How to be able to preserve the new line character even after the conversion to bytes?
Sample Output is :
adding the new line to the string and printing the string gives:
1000458551|A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F|1|7707|0|0|1002|1373569142000|HTC One|val|4.1.2|0|1.01.20130206.15441
1000458551|A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F|1|7707|0|0|1002|1373569142000|HTC One|val|4.1.2|0|1.01.20130206.15441
After converting it to bytes and printing the string
1000458551|A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F|1|7707|0|0|1002|1373569142000|HTC One|val|4.1.2|0|1.01.20130206.154411000458551|A210171046D86F9F6EE21B66FE9B1441E20EC1DEF9654A2D092162591C01D26F|1|7707|0|0|1002|1373569142000|HTC One|val|4.1.2|0|1.01.20130206.15441
Thanks for the reply in advance

Because this line is never executed.
finalRecord.append(rec).append(System.lineSeparator());
I'm not sure why you split string like this:
String Recordstore[] = p.split("\\^\\^");
Obviously, the array Recordstore.length() will always be 1, since there isn't any ^^ in your original string.
So counter != len - 1 will always be false.
update:
I made some changes in this line:
baos.write(finalRecord.append(System.lineSeparator()).toString().getBytes());

Related

xOr decryption replaces correct letter with wrong letter throughout the whole text file

Java: I'm encrypting and decrypting a text file using a key of any two ASCII characters on the keyboard. I have them working correctly, except when I read the encrypted file to a string for decryption. It replaces some specific letter with a different incorrect letter, but not all of correct letters are replaced. Some t's are replaced with s's for example. I've also seen some b's be replaced with e's when I use a different key.
I've already looked through my encrypted/decryption algorithm. I copy and pasted the encrypted text file into my code and ran the algorithm again, it came out perfect. The only time the letters are replaced is when the encrypted algorithm is read from a text file to be decrypted.
public static String readFileToString(string filePath) {
StringBuilder builder = new StringBuilder();
try (Stream<String> stream = Files.get(filePath), StandardCharsets.UTF_8)){
stream.forEach(s->builder.append(s).append("\n");
}
catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
public static void writeFile(String crypt) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("New file name: ");
String fileName = sc.nextLine();
String writtenString = crypt;
String userHome = System.getProperty("user.home");
File textFile = new File(userHome, fileName + ".txt");
BufferedWriter out = new BufferedWriter(new FileWriter(textFile));
out.write(writtenString);
out.close();
//Converts string and key into binary characters for 1-to-1 xOr to prevent any possible translation errors.
public static String crypt(String input, String key) throws UnsupportedEncodingException {
if (input.length() % 2 == 1) {
input = input + " ";
}
int n = input.length() / 2;
key = new String(new char[n]).replace("\0", key);
byte[] a = input.getBytes();
byte[] c = key.getBytes();
StringBuilder binaryBuilder = new StringBuilder();
StringBuilder binaryKeyBuilder = new StringBuilder();
//Creates a StringBuilder of bits using the file text
for(byte b: a) {
int value = b;
for(int i = 0; i < 8; i++) {
binaryBuilder.append((value & 128) == 0 ? 0 : 1);
value <<= 1;
}
binaryBuilder.append(' ');
}
//Converts binary StringBuilder to String
String binary = binaryBuilder.toString();
//Creates a StringBuilder of bits using the provided key
for(byte d: c) {
int keyValue = d;
for(int j = 0; j < 8; j++) {
binaryKeyBuilder.append((keyValue & 128) == 0 ? 0 : 1);
keyValue <<= 1;
}
binaryKeyBuilder.append(' ');
}
//Converts binaryKey StringBuilder to String
String binaryKey = binaryKeyBuilder.toString();
//Creates StringBuilder of bits using the provided key
StringBuilder xOr = new StringBuilder();
for(int q = 0; q < binary.length();q++) {
xOr.append(binary.charAt(q) ^ binaryKey.charAt(q));
}
String xOrResult = xOr.toString();
String cryptedString = "";
char next;
//Iterates through binary string to convert to ASCII characters 8 bits at a time.
for(int k = 0; k <= xOrResult.length()-8; k+=9) {
next = (char)Integer.parseInt(xOrResult.substring(k,k+8), 2);
cryptedString += next;
}
return cryptedString;
}
When I use the key "ty"
"Four score and seven years ago our fathers brought forth on this" is the correct phrasing.
However, I'm getting: "Four score and seven years ago our fashers broughs forth on this"
I would use binary file for encrypted text. It will save you from dealing with UTF-8 encoding/decoding some unusual code points. For example - when you xor 't' and 't' you get character with code 0.
You can also get unexpected new line characters. You actually replace all of them with '\n', but there are other options - '\r', or even two characters in sequence "\r\n". All of them will be replaced with '\n' in your code, and lead to mistakes after decryption.
What happened here:
Binary ASCII (or UTF-8) code for t is 01110100, and for y it is 01111001. When character y from key meets character t from text you get 01110100 xor 01111001 = 00001101 = 0x0D = '\r'. This character is written to file. When you read that file line by line, this '\r' is skipped as line separator. You replace it with '\n'=00001010 in line
stream.forEach(s->builder.append(s).append("\n");
When decrypting that text we get 00001010 (\n) xor 01111001 (y) = 01110011 (s).

how to concatenate two items in array of string using java?

I have a text file i already read it and return an array of string "lines" in this structure
{(1),text,(2),text,(3),text........}
I want to restructure it as
{(1)text,(2)text,(3)text........}
which mean concatenate every number like (1) with the next text and so on
public String[] openFile() throws IOException {
FileInputStream inStream = new FileInputStream(path);
InputStreamReader inReader = new InputStreamReader(inStream,"UTF-8");
BufferedReader textReader = new BufferedReader(inReader);
int numberOfLine = countLines();
String[] textData = new String[numberOfLine];
for (int i = 0; i < numberOfLine; i++) {
// if (textReader.readLine()!= null) {
textData[i] = textReader.readLine();
//}
}
textReader.close();
return textData;
}
how can i do it please using Java language ?
Thanks for your helps and your opinions
String[] newArray = new String[textData.length / 2];
for (int i = 0; i < textData.length - 1; i+=2) {
newArray[i / 2] = textData[i] + textData[i + 1];
}
But be sure that your textData has an even length
Put this snippet before the return statement and return newArray instead;
It seems that the comma you want to omit is always preceded by a closing bracket. Assuming that that is the only time it happens in your string you could just do a simple replacement in your for-loop:
textData[i] = textData[i].replace("),", ")");
If that isn't the case, then another thing you could do is work on the basis that the comma you want to remove is the first in the string:
//Locate index of position of first comma in string
int firstComma = x.indexOf(',');
//Edit string by concatenating the bit of the string before the comma
and the bit after it, stepping over the comma in the process
textData[i] = (textData[i].substring(0, firstComma)).concat(textData[i].substring(firstComma + 1));

Parse byte[] from String initializer "new byte[]{1,2,3}"

Hi Team,Firstly I don't want a byte[] array made from the actual String/char[]
//NO!
String s = "abc";
byte[] bytes = s.getBytes();
I want a byte[] array constructed by the contents and representation of the String, like so.
byte[] b = "new byte[]{1,2,3}"
//Again I don't want >> byte[] b = new String("new byte[]{1,2,3}").getBytes();
thanks Team.
This worked for me -
/**
* Parse a properly formatted String into a byte array.
*
* #param in
* The string to parse - must be formatted
* "new byte[]{1,2,n}"
* #return The byte array parsed from the input string.
*/
public static byte[] parseByteArrayFromString(
String in) {
in = (in != null) ? in.trim() : "";
// Opening stanza.
if (in.startsWith("new byte[]{")) {
// Correct closing brace?
if (in.endsWith("}")) {
// substring the input.
in = in.substring(11, in.length() - 1);
// Create a list of Byte(s).
List<Byte> al = new ArrayList<Byte>();
// Tokenize the input.
StringTokenizer st = new StringTokenizer(in,
",");
while (st.hasMoreTokens()) {
String token = st.nextToken();
// Add a Byte.
al.add(Byte.valueOf(token.trim()));
}
// Convert from the List to an Array.
byte[] ret = new byte[al.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = al.get(i);
}
return ret;
}
}
return new byte[] {};
}
public static void main(String[] args) {
byte[] vals = parseByteArrayFromString("new byte[]{1,2,3}");
System.out.println(Arrays.toString(vals));
}
Well, you could always just traverse through the array and put those values in a string, then put those in a byte array.
String d = "new byte[]{";
for(int i = 0; i < s.length() - 1; i++)
d += s.charAt(i) +",";
d += s.charAt(s.length() - 1) + "}";
byte[] b = d.getBytes();
You can extract bytes by using regular expression, such as:
Pattern pattern = Pattern.compile("(\\d+)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
Byte.parseByte(matcher.group(0)).byteValue(); // Use this
}
In the while loop, use can add them to an array to use it later or print it to console, or any else. It's up to you.
For sure that input string is correct, add another pattern to check that string if necessary. For example:
Pattern.compile("new byte\\[\\] ?\\{((\\d+),? *)+\\}");

incorrect reading of file after socket communication in java

I have this file that I send from a server to a client through a socket. However when I try to reaad the first 159 first bytes in the client it gives a result that is smaller than when I ask the server to read the same amount in the original file, but when I print the length of what I read in both sides it is the same but one is almost 2/3 of the other! What could be the problem? I already made replaceAll("(\\r|\\n|\\s)","") to take off any space or tabulation but still no change.
Any suggestions?
Here is the code where I write the file:
FileOutputStream writer = new FileOutputStream("Splits.txt");
String output= null;
StringBuilder sb2 = new StringBuilder();
for (int i =0; i < MainClass.NUM_OF_SPLITS ; i++){
StringBuilder sb1 = new StringBuilder();
for (String s : MainClass.allSplits.get(i).blocks)
{sb2.append(s);}
sb1.append(sb2);}
output = sb2.toString().replaceAll("(\\r|\\n|\\s)", "");
writer.write(output.getBytes(Charset.forName("ISO-8859-1")));
writer.close();
And here where I read the file:
FileInputStream fis = new FileInputStream("Splits.txt");
InputStreamReader reader = new InputStreamReader(fis,Charset.forName("ISO-8859-1"));
for(int i = 0; i < splitsNum; i++) {
char[] buf = new char[159]; //param
int count = reader.read(buf);
String h=String.valueOf(buf, 0, count).replaceAll("(\\r|\\n||\\s)","");
System.out.println( h);
}
You need to loop until you've read all the data you need:
char[] buf = new char[159];
int charsRead = 0;
while (charsRead < buf.length) {
int count = reader.read(buf, charsRead, buf.length - charsRead);
if (count < 0) {
throw new EOFException();
}
charsRead += count;
}
// Right, now you know you've actually read 159 characters...

java regular expression getting values from a txt file [duplicate]

I am new to Java. I have one text file with below content.
`trace` -
structure(
list(
"a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)),
"b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.379787,-0.105249,1.0063,0.613083,-0.165703,0.695775))
)
)
Now what I want is, I need to get "a" and "b" as two different array list.
You need to read the file line by line. It is done with a BufferedReader like this :
try {
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int lineNumber = 0;
double [] a = null;
double [] b = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
lineNumber++;
if( lineNumber == 4 ){
a = getDoubleArray(strLine);
}else if( lineNumber == 5 ){
b = getDoubleArray(strLine);
}
}
// Close the input stream
in.close();
//print the contents of a
for(int i = 0; i < a.length; i++){
System.out.println("a["+i+"] = "+a[i]);
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Assuming your "a" and"b" are on the fourth and fifth line of the file, you need to call a method when these lines are met that will return an array of double :
private static double[] getDoubleArray(String strLine) {
double[] a;
String[] split = strLine.split("[,)]"); //split the line at the ',' and ')' characters
a = new double[split.length-1];
for(int i = 0; i < a.length; i++){
a[i] = Double.parseDouble(split[i+1]); //get the double value of the String
}
return a;
}
Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.
You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:
Array[] first= line.split("("); //first[2] will contain the values
Then:
Array[] arrayList = first[2].split(",");
You will have the numbers in arrayList[]. Be carefull with the final brackets )), because they have a "," right after. But that is code depuration and it is your mission. I gave you the idea.

Categories

Resources