I have a file with many lines.
Ex :
toto = 0x0020 tata 0x2000 0x0003
tata = 0x0001
tututtt = 0x0021
=> 0x3200
I just want to have these hexadecimal values in a byte array.
I've tried to use a BufferReader and split lines with the " " but I need to find a way to keep exclusively hexadecimal values.
Thanks in advance for your help.
I'd go with java.util.Scanner which can read tokens and patterns, here is the code that can read the file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ReadOnlyHex {
private static Pattern pattern = Pattern.compile("0x\\d{4}");
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("c:/temp/input.txt"));
while(in.hasNextLine()) {
String token = in.findInLine(pattern);
if (token == null) {
in.nextLine();
continue;
}
System.out.println(token.getBytes());
}
in.close();
}
}
I can only assume you are looking for the bytes array of the string, which can be achieved with String.getBytes()
Otherwise, the value represents an int that can be later changed to Integer.toBinaryString
You can use a regex pattern to filter. Loop over the line and use filter function in if you are using Java8.
So first define your pattern
final Pattern p= Pattern.compile("0x[0-9A-F]+$");
Then you can filter your each line array as
String[] splitLineArray=line.split(" ");
String[] hexNumbers=Arrays.stream(splitLineArray).filter((s)-> p.matcher(s).matches()).toArray();
This will return a new array with only hex numbers.
Related
This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(16 answers)
Closed 1 year ago.
I am trying to split a .txt file into an array so I can access individual elements from it. However I get the following error, Index 1 out of bounds for length 1 at babySort.main(babySort.java:21).
I am unsure where I am going wrong because I used the same code on a test string earlier and it splits into the appropriate amount of elements.
I suspect it has something to do with the while loop, but I can't seem to wrap my mind around it, any help would be appreciated.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class babySort {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("src/babynames.txt");
Scanner in = new Scanner(inputFile);
String test = "Why wont this work?";
String[] test2 = test.split("\\s+");
System.out.println(test2[2]);
while (in.hasNext()) {
String input = in.next();
String[] inputSplit = input.split("\\s+");
//System.out.println(Arrays.toString(inputSplit));
System.out.println(inputSplit[1]);
}
}
}
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
My understanding is that you want to read the input line-by-line. You can use FileReader instead of Scanner to read the file line-by-line. You can also use BufferedReader like so:
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
String input;
while ((input = br.readLine()) != null) {
// process the line
String[] inputSplit = input.split("\\s+");
//System.out.println(Arrays.toString(inputSplit));
System.out.println(inputSplit[1]);
}
}
I have a .txt file which looks like 43 78 63 73 99 ....i.e.,
all its values are separated by spaces.
I want each of them to be added into an array,such that
a[0]=43
a[1]='78
a[2]=63 and so on.
How can I do this in Java..Please explain
Read the file into a string. Then spilt the string on the space into a string array.
Use a filereader to read in the values
E.g.
Scanner sc = new Scanner(new File("yourFile.txt"));
Then you read all the integers from the file and put them into an integer array.
Java Scanner class documentation
Java File class
Well I would do it by storing the text file into a string. (as long as it's not too big) Then I would just use .split(" ") to store it into an array.
Like this:
String contents = "12 32 53 23 36 43";
//pretend this reads from file
String[] a = contents.split(" ");
Now the array 'a' should have all the values stored in it. If you want the array to be an int, you could use an int array, and use Integer.toString() to convert data types.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class readTextToIntArray {
public static void main(String... args) throws IOException {
BufferedReader reader=new BufferedReader(new FileReader("/Users/GoForce5500/Documents/num.txt"));
String content;
List<String> contentList=new ArrayList<String>();
while((content=reader.readLine())!=null){
for(String column:content.split(" ")) {
contentList.add(column);
}
}
int[] result=new int[contentList.size()];
for(int x=0;x<contentList.size();x++){
result[x]=Integer.parseInt(contentList.get(x));
}
}
}
You may use this.
I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks
Ok so I'm trying to create a programmed where the user is asked to enter a word, this word is then stored as a variable, and then its displayed as an array.
This is what I have so far:
package coffeearray;
import java.util.Arrays;
import java.util.Scanner;
import java.lang.String;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String drink;
String coffee;
int [] a =new int[6];
Scanner in = new Scanner(System.in);
System.out.println("Please input the word coffee");
drink = in.next();
So basically I need some code so that the word stored is then displayed as variable. For example "Coffee" would then be displayed but each letter on its own line.
I've searched all over and can't seem to find out how to do this. Thanks in advance.
Given string str :
String str = "someString"; //this is the input from user trough scanner
char[] charArray = str.toCharArray();
Just iterate trough character array. I'm not going to show you this as this can easily be googled. Again if you're really stuck let me know, but you should really know this.
Update
Since you're new to Java. Here is the code per Jeff Hawthorne comment :
(for int i=0, i < charArray.getlength(); i++){
System.out.println(charArray[i]);
}
You can use String.split("")
Try this:
String word = "coffee"; //you get this from your scanner
if(word.length()>0)
String [] characterArray = Arrays.copyOfRange(word.split(""), 1, word.length()+1);
You can convert the String to a CharSequence:
CharSequence chars = inputString.subSequence(0, inputString.length()-1);
you can then iterate over the sequence, or get individual characters using the charAt() method.
I'm reading in two lines of a .txt file (ui.UIAuxiliaryMethods; is used for this) to calculate the BodyMassIndex(BMI) of patients, but I get a inputmismatchexception when the patientLenght is reached. These are my two lines of input, seperated by a \t:
Daan Jansen M 1.78 83
Sophie Mulder V 1.69 60
It's sorted in Name - Sex - Length - Weight. This is my code to save all elements in strings, doubles and integers:
package practicum5;
import java.util.Scanner;
import java.io.PrintStream;
import ui.UIAuxiliaryMethods;
public class BodyMassIndex {
PrintStream out;
BodyMassIndex() {
out = new PrintStream(System.out);
UIAuxiliaryMethods.askUserForInput();
}
void start() {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String lineDevider = in.nextLine(); //Saves each line in a string
Scanner lineScanner = new Scanner(lineDevider);
lineScanner.useDelimiter("\t");
while(lineScanner.hasNext()) {
String patientNames = lineScanner.next();
String patientSex = lineScanner.next();
double patientLength = lineScanner.nextDouble();
int patientWeight = lineScanner.nextInt();
}
}
in.close();
}
public static void main(String[] args) {
new BodyMassIndex().start();
}
}
Somebody got a solution for this?
Your name has two tokens not one, so lineScanner.next() will only get the token for the first name.
Since a name can have more than 2 tokens theoretically, consider using String.split(...) instead and then parsing the last two tokens as numbers, double and int respectively, the third from last token for sex, and the remaining tokens for the name.
One other problem is that you're not closing your lineScanner object when you're done using it, and so if you continue to use this object, don't forget to release its resource when done.
Your name field has two token. and you are trying to treat them as one. that;s creating the problem.
You may use a " (double quote) to separate the name value from others. String tokenizer may do your work.
I changed the dots to commas in the input file. Hooray.