I'm handling a Bluetooth connection with Android and I'd like to read the InputStream buffer until I get some specific character like '\n' (new line) or any other character and leave the buffer as it is, then read the following bytes again until the same character is read in order to place them in separate strings. I tried several ways with no success, can anybody help me?
The code I'm using to get the data is the following
public String getData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inStream.read(inString);
}
catch (IOException e){
e.printStackTrace();
}
String str= new String(inString, StandardCharsets.UTF_8);
return str;
}
If you want to read until you find a specific char,
one solution could be something like this:
public static String readUntilChar(InputStream stream, char target) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader buffer=new BufferedReader(new InputStreamReader(stream));
int r;
while ((r = buffer.read()) != -1) {
char c = (char) r;
if (c == target)
break;
sb.append(c);
}
System.out.println(sb.toString());
} catch(IOException e) {
// Error handling
}
return sb.toString();
}
Finally, I got a solution. I don't know if it's the most optimum, but it works fine. I post the code in case it's useful for someone else. Thanks for your responses.
Function to get the input stream char by char:
public char getData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inStream.read(inString,0,1);
}
catch (IOException e){
e.printStackTrace();
}
String str= new String(inString, StandardCharsets.UTF_8);
inChar=str.charAt(0);
return inChar;
}
Function to get the desired strings when the character '&' appears:
public void procesChar(char inChar){
if(inChar=='&'){
String str=new String(charBuffer);
countBytes=0;
Arrays.fill(charBuffer,(char)-1);
}
else {
charBuffer[countBytes] = inChar;
countBytes++;
}
}
Related
I have a program and one of the methods I use is for counting the lines a .txt file has and return an integer value. The problem is when I execute it, despite I wrote if my line is == null the while has to stop, the while loop keeps going, ignoring the nulls it gets infinitely.
I don't know what to do to try to solve it.
private int sizeOfFile (File txt) {
FileReader input = null;
BufferedReader count = null;
int result = 0;
try {
input = new FileReader(txt);
count = new BufferedReader(input);
while(count != null){
String line = count.readLine();
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
input.close();
count.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
It has to stop when it detects a null, which means there are no more lines, but it keeps going.
When you instantiate a BuffereReader assign it to count, count will always be non-null and hence will satisfy the while loop:
count = new BufferedReader(input); //count is holding an instance of BufferedReader.
while(count != null){ //here count is non-null and while loop is infinite and program never exits.
Instead use the following code, where the each line will be read and checked whether it is null, if null then the program will exit.:
input = new FileReader(txt);
count = new BufferedReader(input);
String line = null;
while(( line = count.readLine())!= null){ //each line is read and assigned to the String line variable.
System.out.println(line);
result++;
}
If you are using JDK-1.8 you can shorten your code using the Files API:
int result = 0;
try (Stream<String> stream = Files.lines(Paths.get(txt.getAbsolutePath()))) {
//either print the lines or take the count.
//stream.forEach(System.out::println);
result = (int)stream.count();
} catch (IOException e) {
e.printStackTrace();
}
count is your BufferedReader, your loop should be on line! Like,
String line = "";
while (line != null) {
line = count.readLine();
Also, you should use try-with-Resources to close your resources (instead of the finally block). And you could write that while loop more idiomatically. Like,
private int sizeOfFile(File txt) {
int result = 0;
try (BufferedReader count = new BufferedReader(new FileReader(txt))) {
String line;
while ((line = count.readLine()) != null) {
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
I want to excrypt a file in java very basically. Simply read line by line the file, and change the value of the chars to "char += key", where key is an integer.
The problem is that if I use a key larger or equal with 2, it doesn't work anymore.
public void encryptData(int key) {
System.out.println("Encrypt");
try {
BufferedReader br = new BufferedReader(new FileReader("encrypted.data"));
BufferedWriter out = new BufferedWriter(new FileWriter("temp_encrypted.data"));
String str;
while ((str = br.readLine()) != null) {
char[] str_array = str.toCharArray();
// Encrypt one line
for (int i = 0; i < str.length(); i++) {
str_array[i] += key;
}
// Put the line in temp file
str = String.valueOf(str_array);
out.write(str_array);
}
br.close();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
The decrypt function is the same but with the input/output files interchanged and instead of adding the key value, I subtract it.
I check char by char and indeed, the header gets messed up when i use a key value > 1. Any ideas? Is it because of maximum value of the char being exceeded?
You're basically implementing a general-purpose Caesar cipher.
Adding a number to a character could change a character to newline, etc which will not work if using a BufferedReader to read it back in.
Best to manipulate the text as a byte stream which would correctly encode and decode newline and any non-ASCII characters.
public void encryptData(int key) {
System.out.println("Encrypt");
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("raw-text.data"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("temp_encrypted.data"));
int ch;
while((ch = in.read()) != -1) {
// NOTE: write(int) method casts int to byte
out.write(ch + key);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void decryptData(int key) {
System.out.println("Decrypt");
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("temp_encrypted.data"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("decrypted.data"));
int ch;
while((ch = in.read()) != -1) {
out.write(ch - key);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
I'm trying to implement a java server with http frames, I have a couple of URI's : /login.jsp and /logout.jsp that are found in the Request URi of the http format.
When I send the logout request to the Server I send it with a header like so:
Cookie: user_auth="SomeCookie".
Here is the code:
public HttpMessage nextMessage() {
if (!isAlive()) {
try {
throw new IOException("Tokenizer is Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
// Return String
HttpMessage newMessage = null;
String output = null;
StringBuilder stringBuilder = new StringBuilder();
try {
int c;
while ((c = this.fInputStream.read()) != -1) {
if (c == this.fDelimiter)
break;
else
stringBuilder.append((char) c);
}
// Create an HttpMessage from the information received
output = stringBuilder.toString();
} catch (IOException e) {
this.fClosed = true;
try {
throw new IOException("Connection is Dead");
} catch (IOException e1) {
e1.printStackTrace();
}
}
newMessage = parseHttp(output);
return newMessage;
}
The parseHttp method breaks the type, and headers apart.
But the problem is after sending the login action to the server, if I try send the logout action the parsed information stored in the string builder has missing characters(more specifically the RequestType, RequestURI and the HttpVersion ) are missing and only the header can be found.
In addition if I try to print each characters I receive from the inputStream at the time I see all the characters that are supposed to be in the frame.
Are you sure you want the break; line and not a continue; break will cause the while loop to exit while using continue will simply skip the else and run the next iteration of the while loop.
Following code prints all the missing characters in a given string by removing duplicates.
import java.util.*;
public class MissChars
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
StringBuffer sb=new StringBuffer();
char c[]=str.toCharArray();
LinkedHashSet<Character> set=new LinkedHashSet<Character>();
for(int i=0;i<c.length;i++)
set.add(c[i]);
for(char cc:set)
sb.append(cc);
String sss=new String(sb);
char arr[]=sss.toCharArray();
for(char i='a';i<='z';i++)
{
for(int j=0;j<arr.length;j++)
{
if(i!=arr[j])
count++;
if(count==arr.length)
System.out.print(i);
}
count=0;
}
}
}
I'm attempting to read in every character (tabs, new lines) in a text file. I'm having some trouble reading all of these in. My current method reads the tabs in but not new lines. Here is the code:
//reads each character in as an integer value returns an arraylist with each value
public static ArrayList<Integer> readFile(String file) {
FileReader fr = null;
ArrayList<Integer> chars = new ArrayList<Integer>(); //to be returned containing all commands in the file
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int tempChar = ' ';
String tempLine = "";
while ((tempLine = br.readLine()) != null) {
for (int i = 0; i < tempLine.length(); i++) {
int tempIntValue = tempLine.charAt(i);
chars.add(tempIntValue);
}
}
fr.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
I originally used the read() method instead of readLine() but that had the same problem. I'm representing the char as ints. Any help is really appreciated!
I suggest you use try-with-resources, List and the diamond operator <> and that you read each char with the BufferedReader.read() method.
public static List<Integer> readFile(String file) {
List<Integer> chars = new ArrayList<>();
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);) {
int ch;
while ((ch = br.read()) != -1) {
chars.add(ch);
}
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
The reason you aren't getting line endings is documented by the BufferedReader.readLine() Javadoc which says in part (emphasis added),
A String containing the contents of the line, not including any line-termination characters...
If I am scanning from a text
Scanner s= new Scanner("texto.txt");
// I want to compare the next char from the line with a <
// like this:
if(s.nextChar().equals("<")){
.....
I know that s.nextChar() does not exist but there is any similar thing to use in this case?
Your code would something like...
Scanner s= new Scanner("texto.txt");
s.useDelimiter("");
while (s.hasNext()) {
if(s.nextChar()=='<'){
.....
}
Note that after the call of s.nextChar(), the value is actually fetched, so its better to keep the variable, if you would like to use it further, like:
char ch = s.nextChar();
Consider dumping Scanner and using FileReader:
FileReader fileReader = new FileReader("textto.txt");
int charRead
while( (charRead = fileReader.read()) != -1)
{
if(charRead == '<')
{
//do something
}
}
FileReader reader = null;
try {
reader = new FileReader("");
int ch = reader.read() ;
while (ch != -1) {
// check for your char here
}
} catch (FileNotFoundException ex) {
//
} catch (IOException ex) {
//
} finally {
try {
reader.close();
} catch (IOException ex) {
//
}
}