Replace a newline character stored in an array of Strings [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Consider the following 2D array of Strings a[5][5],
I store three values in the first three blocks in the array "a".
When I print my array, I get the following output.
ABC
null
DEF
null
These values are present in a file and I retrieve the values and store them in an array of strings.
The file ("file.txt")looks like this,
A B C
D E F
Here is my code,
Declaration:
static String [][] a= new String [4][4];
public static String newline = System.getProperty("line.separator");
private static int i,j;
Main code:
i=j=0;
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
while((c = (char)br.read()) != (char)-1)
{
if (c != ' ' && c != (char)'\n')
{
a[i][j] = Character.toString(c);
j++;
}
else if (c == '\n')
{
i++;
j = 0;
}
}
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
if (newline.equals(a[i][j]))
{
mainArray[i][j] = null;
}
}
}
Here is how I print my array,
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
System.out.print(a[i][j]);
}
System.out.println("");
}
My desired output should be,
ABCnullnull
DEFnullnull
Is there a better way to work on this problem??

BufferedReader has a readLine() method that will return a string with all the chars preceding the \n or \r. It also returns null at the end of the stream.
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
List<String> list = new ArrayList<String>();
String line;
while ((line= br.readLine())!=null)
{
list.add(line);
}
This will cope with any number of returns and arbitrary length strings.
Or if you must have each line as and array
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
List<char[]> list = new ArrayList<char[]>();
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()) list.add(line.toCharArray());
}
Reading your file should result in a List size of two each containing and array of 5 chars. ['A',' ','B',' ','C'] then ['D',' ','E',' ','F']

Try
public static String newline = System.getProperty("line.separator");
for (int i=0;i<5;i++)
{
if (newline.equals(a[i]))
{
a[i] = null;
}
}

EDITED ANSWER:
From reading your responses and looking at what your expected output is, you may be better off doing something like this...
pseudo-code
read entire line into String array index
Before printing, check length of String (a[i].length)
If length is less than 5, add 'null' to the end of the String for every character less than 5
Thus:
if(a[i].length < 5)
{
int index = 5 - a[i].length;
for( ; index > 0; index --)
{
a[i].concat("null");
}
}
ORIGINAL ANSWER............
Not sure if my comment was sent to you or not. You might just be indexing too far out.
Try
for(int i = 0; i < 4; i++)
System.print(a[i]);

Related

How can I read every letter from the file?

I have this part of code. I can read all lines from the code. But I want take (read) every letter separately and put it into array. How can I do it?
For Example: In file are numbers 00010 and I want put it into array like this: array[0,0,0,1,0]
public void readTest()
{
try
{
InputStream is = getResources().getAssets().open("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String st = "";
StringBuilder sb = new StringBuilder();
while ((st=br.readLine())!=null)
{
sb.append(st);
}
br.close();
}catch (IOException e)
{
Log.d(TAG, "Error: " + e);
}
}
Use br.read(). It returns the character as integer
ArrayList<char> charArray = new ArrayList<>();
int i;
while ((i = br.read()) != -1) {
char c = (char) i;
charArray.add(c);
}
Straight from the JavaDoc:
public int read()
throws IOException -
Reads a single character.
You should add read every string and add it's letters to array by iterating through it, like this:
while ((st=br.readLine())!=null) {
sb.append(st);
for (int i = 0; i < st.length(); i++) {
char c = st.charAt(i);
yourArray.add(c);
}
}

How to read N amount of lines from a file?

I am trying to practice reading text from a file in java. I am little stuck on how I can read N amount of lines, say the first 10 lines in a file and then add the lines in an ArrayList.
Say for example, the file contains 1-100 numbers, like so;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ....
I want to read the first 5 numbers, so 1,2,3,4,5 and add it to an array list. So far, this is what I have managed to do but I am stuck and have no clue what to do now.
ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));
for (double i = 0; i <= 5; ++i) {
// I know I need to add something here so the for loop read through
// the file but I have no idea how I can do this
array.add(i); // This is saying read 1 line and add it to arraylist,
// then read read second and so on
}
You could try using a Scanner and a counter:
ArrayList<Double> array = new ArrayList<Double>();
Scanner input = new Scanner(new File("numbers.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 10)
{
array.add(Double.parseDouble(input.nextLine()));
counter++;
}
This should loop through 10 lines adding each to the arraylist as long as there is more inputs in the file.
See this How to read a large text file line by line using Java?
I think this will work:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
if (i < 5)
{
// process the line.
i++;
}
}
br.close();
ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
System.err.println(ex.toString());
//here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
//read line by line with the readLine() method
while ((line = reader.readLine()) != null && counter < N) {
//check also the counter if it is smaller then desired amount of lines to read
array.add(line); //add the line to the ArrayList of strings
counter++; //update the counter of the read lines (increment by one)
}
//the while loop will exit if:
// there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
// OR the desired amount of line was correctly read
reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
System.err.println(ex.toString());
}
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("numbers.txt")))) {
for (int i = 0; i < 5; ++i) { // Loops 5 times
String line = in.readLine();
if (line == null) [ // End of file?
break;
}
// line does not contain line-ending.
int num = Integer.parseInt(line);
array.add(i);
}
} // Closes in.
System.out.println(array);
You can do this with:
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
// do something with the list here
}
As complete example as JUnit test:
public class ReadFirstLinesOfFileTest {
#Test
public void shouldReadFirstTenNumbers() throws Exception {
Path p = Paths.get("numbers.txt");
Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
}
}
}
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
myList.add(fileScanner.nextDouble());
}
Make sure you have "numberOfLinesToRead" lines in your file.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> nlines = IntStream.range(0, hlines)
.mapToObj(i -> readLine(br)).collect(Collectors.toList());
String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

java read integers from text file

I am using eclipse ; I need to read integers from a text file that may have many lines of numbers separated by space : 71 57 99 ...
I need to get these numbers as 71 and 57 ...but my code produces numbers in the range 10 to 57
int size = 0;
int[] spect = null;
try {
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
size = is.available();
spect = new int[size];
for (int si = 0; si < size; si++) {
spect[si] = (int) is.read();// System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print(e.getMessage());
}
read() reads single byte and then you are converting into int value, you need to read line by line using BufferedReader and then split() and Integer.parseInt()
Have you considered using a Scanner to do this? Scanner can take the name of the file as the parameter and can easily read out each individual number.
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
int[] spect = new int[is.available()];
Scanner fileScanner = new Scanner("/dataset.txt");
for(int i = 0; fileScanner.hasNextInt(); i++){
spect[i] = fileScanner.nextInt();
}
You may convert it to a BufferedReader and read and split the lines.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null) {
String[] strings = line.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
//do what you need with the Integer
}
}

Trying to find the nth element to the last from a list (with a file input)

Input would look like
a b c d 4
e f g h 2
where each line would be read like a list and integer representing as an index in the list
I first try to read the file line be line and store it in the list. Heres what i have
public class FileReader {
public static void main(String[] args) {
String line = null;
List<String> list = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream("test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// File file = new File("test.txt");
// Scanner scanner = new Scanner(file);
while ((line = br.readLine()) != null) {
list.add(line);
}
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now i want to remove the white spaces from the list and store the values in char array and then i was planning on traversing that array backwards till the nth element, depending on the input for n.
String[] elements = line.trim().split("\\s");
char[] chars = new char[elements.length - 1];
int i= Integer.parseInt(elements[elements.length - 1]);
for (i = 0; i < elements.length - 1; i++)
char[i] = elements[i].charAt(i);
Someone provided me this piece of code earlier and i tried it and it throws a nullpointerexception at String[] elements.
It's because you are running until line is null here
while((line = br.readLine()) != null)
{
list.add(line);
}
And then you are trying to call .trim() on it.
Do you mean to be processing the strings in list instead?
If so try looping over you list, you are already splitting it correctly and getting the last element. All you need to do is caluclate the offset, in this case it will be the length - 1 - the last element, in you String[] elements and you can print that out.
for (int i = 0; i < list.size(); i++)
{
String currentLine = list.get(i);
String[] elements = currentLine.trim().split("\\s");
int lastElement = Integer.parseInt(elements[elements.length - 1]);
String desiredValue = elements[elements.length - 1 - lastElement];
System.out.println("desiredValue = " + desiredValue);
}
You can avoid most of the work you're doing. I don't know if your input will require much flexibility (code to that if necessary) but in your example you only have 1 digit for the index.
Just avoid all the traversing and looping entirely:
String currentLine = file.nextLine();
//Find value from last space in the string, until the end of the string (will be the number)
int index = Integer.parseInt(currentLine.substring(
currentLine.lastIndexOf(' ') + 1, currentLine.length()));
//Remove all spaces from the current line
currentLine = currentLine.replaceAll("\\s+","");
//Remove the index at the end from the string, leaving only the characters
currentLine = currentLine.substring(0, currentLine.indexOf(index + ""));
char desiredValue = currentLine.charAt(currentLine.length() - index);
System.out.println("desiredValue = " + desiredValue);
This saves a lot of adding stuff to arrays if none of that is needed later, just do it all the first time through.

Matrix from File

I am trying to create a matrix from a text file. The problem is that when the Buffered Reader function readline() is done parsing first line of file it comes to second line but the its reading it as empty which it is not.
void covar()
{
double [][]covar=new double[10][5];
int i=0;
int j=0;
try
{
FileInputStream fstream = new FileInputStream("class 1\\feature_vector.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String input;
while((input=br.readLine())!= null)
{
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][j]= new Double(temp[0]);
covar[i+1][j]=new Double(temp[1]);
covar[i+2][j]=new Double(temp[2]);
covar[i+3][j]=new Double(temp[3]);
covar[i+4][j]=new Double(temp[4]);
//i=0;
j++;
}
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Above is the code. The file name is perfect and nothing is wrong with the stream thing. Can you guys help me out with what is wrong with this.
Here is the content of the file:
0.75,321.0,0.22429906,0.97507787,1.966202512778112
0.33333334,135.0,-0.014814815,1.0,5.323770568766052
0.64285713,311.0,0.025723472,1.0,4.764298570227433
0.6,188.0,0.03723404,1.0,4.7349608150168105
0.25,189.0,0.16931216,0.98941797,7.15681209803803
0.71428573,194.0,-0.26804122,0.96391755,5.1654456838422425
0.6,173.0,0.028901733,1.0,6.54275787030257
0.2857143,257.0,0.031128405,1.0,6.095356508899233
0.23076923,197.0,-0.04568528,1.0,3.784908227189768
0.18181819,231.0,0.17316018,0.987013,5.956322938602553
There are two things that are obviously wrong:
You do not need variable i, because one of the dimensions is fixed, and you "unrolled" the loop five times
You swapped the indexes: j should go first, that's the one changing from 0 to 9.
For example:
String [] temp=input.split(",");
covar[j][0] = new Double(temp[0]);
covar[j][1] =new Double(temp[1]);
covar[j][2] =new Double(temp[2]);
covar[j][3] =new Double(temp[3]);
covar[j][4] =new Double(temp[4]);
You could put the loop back to shorten your code:
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
It looks like you are using the wrong indicies for you matrix, I think it should be something like this:
int i = 0;
while((input=br.readLine())!= null) {
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][0]= new Double(temp[0]);
covar[i][1]=new Double(temp[1]);
covar[i][2]=new Double(temp[2]);
covar[i][3]=new Double(temp[3]);
covar[i][4]=new Double(temp[4]);
++i;
}
Your file might have some strange line-terminators that are making the reader think there is an extra line.
You can try to just make your code skip blank lines:
while((input=br.readLine())!= null) {
if( input.length() > 0 ){
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
}
++j;
}

Categories