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.
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 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.
I am trying to split a read in file and put it into a 2d array. The file has 3 strings on each
line seperated by a comma, the overall idea is to arrange this with a sorting algorithm but i cant split the strings, its driving me nuts, can anyone help.
/**
*
*
* #author (your name)
* #version (a version number or a date)
*/
import java.util.*;
import java.lang.String;
import java.util.ArrayList;
import java.util.Arrays;
public class Example2{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/ratings.csv");
String[] sep = new String[inputs.length];
for(int i=0;i<inputs.length;i++){
sep[i]=inputs.split(",");
System.out.println(sep[i]);
}
try{
reader.save("C://somefile.csv",inputs);
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
splitis a method in the String class, and inputs is an array of strings. An array access is expected there. You probably just forgot to add [i] in the code. Also, since you are splitting a string in a loop, you are creating a 2D array of strings, which means sep should be a String[][]. Have a go with this.
public class Example2{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/ratings.csv");
String[][] sep = new String[inputs.length][];
for(int i=0;i<inputs.length;i++){
sep[i]=inputs[i].split(",");
System.out.println(Arrays.toString(sep[i]));
}
}
// ...
}
}
I don't know what are you returning but .split will split sep into a list
this code is correct
sep[i]=inputs.split(",");
but here is your problem
String[] sep = new String[inputs.length];
this is 1 dimensional array but you need 2 dimensional array
answer:
String[][] sep = new String[inputs.length][];
this is just to fix the .split problem
Preface: This is for an assignment in one of my classes.
I need to parse through a CSV file and add each string to an ArrayList so I can interact with each string individually with pre-coded functions.
My problem is that the final string in each line (which doesn't end with a comma) is combined with the first string in the next line and recognized as being at the same index in the ArrayList. I need to learn how to either add a line break or do something else that will stop my loop at the end of each line and read the next line separately. Perhaps there is a built-in method in the scanner class that I'm unaware of that does this for me? Help is appreciated!
Here is the information in the CSV file:
Fname,Lname,CompanyName,Balance,InterestRate,AccountInception
Sally,Sellers,Seashells Down By The Seashore,100.36,3,7/16/2002
Michael,Jordan,Jordan Inc.,1000000000,3,6/12/1998
Ignatio,Freely,Penultimate Designs,2300.76,2.4,3/13/1991
Here is my code so far
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("smalltestdata-sallysellers.csv"));
// Chomp off at each new line, then add to array or arraylist
scanner.useDelimiter("\n");
ArrayList<String> data = new ArrayList<String>();
while (scanner.hasNext()) {
// Grab data between commas to add to ArrayList
scanner.useDelimiter(",");
// Add grabbed data to ArrayList
data.add(scanner.next());
}
System.out.println(data.get(10));
scanner.close();
}
}
And here is the output
7/16/2002
Michael
It seems like you just need to do...
String s[] = scanner.nextLine().split(",");
Collections.addAll(data, s);
let me start off by saying that I am a fairly new Java programmer, and what I am trying to attempt is a bit over my head. Thus, I came here to try to learn it.
Okay, so here's the issue: I am trying to build a program that makes a 2d array from values in a text document. The text document has three columns and many rows (100+)...basically a [3][i] array.
Here's what I can do: I understand how to read the text file using bufferedReader. Here is a sample program I have that prints the text exactly how it looks in the text file (I apologize ahead for bad formatting; it's my first time on these forums):
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("RA.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] nums = line.split(",");
for (String str : nums) {
System.out.println(str);
}
}
br.close();
}
}
This is what is printed:
00 03 57.504
02 04 03.796
00 06 03.386
03 17 43.059
00 52 49.199
05 52 49.555
etc, etc.
Please help me in making an array with values. Thank you!
define a list outside your while loop like
List list = new LinkedList();
Inside your while loop, add the splitted array to the list, like
list.add(line.split(","));
After the while loop convert your list to an array, resulting in a 2D array:
Foo[] array = list.toArray(new Foo[list.size()]);