I have the following code already, which goes as far as appending the doubles.
Scanner sc1 = new Scanner(System.in);
try {
System.out.println("Enter filename:");
String name = sc1.nextLine();//determines name of file
File file = new File(name);//creates above file
FileReader fileReader = new FileReader(file);//file is read
BufferedReader bufferedReader = new BufferedReader(fileReader );//BufferReader reads file, line by line
StringBuffer stringBuffer = new StringBuffer();//appended to StringBuffer
String line;//reads each
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
The code reads a file that has a double on each line
ex:
1
2
3
4
5
...
How do I store each of these doubles into an array?
If you want to stick to using Array only, convert StringBuffer to String[] like this:
String [] stringArray = stringBuffer.split("\n");
Then convert string array to double array:
Double [] doubleArray = new Double[stringArray.size];
for(int i=0 : i < stringArray.size : i++){
doubleArray[i] = Doube.parseDouble(stringArray[i]);
}
If you must use StringBuffer, you can divide into array by StringTokenizer class.
Alternatively, you can use String instead of StringBuffer and then split() method will work with de-limiter.
You could use an ArrayList:
ArrayList<Double> doubles = new ArrayList<Double>();
while ((line = bufferedReader.readLine()) != null)
{
doubles.add(Double.parseDouble(line));
}
Basic solution
ArrayList<Double> doubles = new ArrayList<>();
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
try{
double value = Double.parseDouble(line );
doubles.add(value);
} catch(NullPointerException e){
//null string
} catch(NumberFormatException e){
//no parsable on the current line
}
}
I don't get the problem...Just make an array that stores the contents of the line as the file is read.
Related
I have a text file with state-city values:-
These are the contents in my file:-
Madhya Pradesh-Bhopal
Goa-Bicholim
Andhra Pradesh-Guntur
I want to split the state and the city... Here is my code
FileInputStream fis= new FileInputStream("StateCityDetails.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int h=0;
String s;
String[] str=null;
byte[] b= new byte[1024];
while((h=bis.read(b))!=-1){
s= new String(b,0,h);
str= s.split("-");
}
for(int i=0; i<str.length;i++){
System.out.println(str[1]); ------> the value at 1 is Bhopal Goa
}
}
Also I have a space between Madhya Pradesh..
So i want to Remove spaces between the states in the file and also split the state and city and obtain this result:-
str[0]----> MadhyaPradesh
str[1]----> Bhopal
str[2]-----> Goa
str[3]----->Bicholim
Please Help..Thank you in advance :)
I would use a BufferedReader here, rather than the way you are doing it. The code snippet below reads each line, split on hyphen (-), and removes all whitespace from each part. Each component is entered into a list, in left to right (and top to bottom) order. The list is converted to an array at the end in case you need this.
List<String> names = new ArrayList<String>();
BufferedReader br = null;
try {
String currLine;
br = new BufferedReader(new FileReader("StateCityDetails.txt"));
while ((currLine = br.readLine()) != null) {
String[] parts = currLine.split("-");
for (int i=0; i < parts.length; ++i) {
names.add(parts[i].replaceAll(" ", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// convert the List to an array of String (if you require it)
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
// print out result
for (String val : nameArr) {
System.out.println(val);
}
I'm trying to read a large text file in the form of:
datadfqsjmqfqs+dataqfsdqjsdgjheqf+qsdfklmhvqziolkdsfnqsdfmqdsnfqsdf+qsjfqsdfmsqdjkgfqdsfqdfsqdfqdfssdqdsfqdfsqdsfqdfsqdfs+qsfddkmgqjshfdfhsqdflmlkqsdfqdqdf+
I want to read this string in the text file as one big java String. Is this possible? I know the use of the split method.
It worked to read it line by line, but what I really need is to split this long text-string at the '+' sign. Afterwards I want to store it as an array, arraylist, list,...
Can anyone help me with this? Because every information on the internet is just about reading a file line by line.
Thanks in advance!
String inpStr = "datadfqsjmqfqs+dataqfsdqjsdgjheqf+qsdfklmhvqziolkdsfnqsdfmqdsnfqsdf+qsjfqsdfmsqdjkgfqdsfqdfsqdfqdfssdqdsfqdfsqdsfqdfsqdfs+qsfddkmgqjshfdfhsqdflmlkqsdfqdqdf+";
String[] inpStrArr = inpStr.split("+");
Hope this is what you need.
You can read file using BufferedReader or any IO-classes.suppose you have that String in testing.txt file then by reading each line from file you can split it by separator (+). and iterate over array and print.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));//file name with path
while ((sCurrentLine = br.readLine()) != null) {
String[] strArr = sCurrentLine.split("\\+");
for(String str:strArr){
System.out.println(str);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It seems to me like your problem is that you don't want to read the file line by line. So instead, try reading it in parts (say 20 characters each time and building your string):
char[] c = new char[20]; //best to save 20 as a final static somewhere
ArrayList<String> strings = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(filename));
while (br.read(c) == 20) {
String str = new String(c);
if (str.contains("+") {
String[] parts = str.split("\\+");
sb.append(parts[0]);
strings.add(sb.toString());
//init new StringBuilder:
sb = new StringBuilder();
sb.add(parts[1]);
} else {
sb.append(str);
}
}
You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller
How many characters can a Java String have?
Try this one:
private static void readLongString(File file){
ArrayList<String> list = new ArrayList<String>();
StringBuilder builder = new StringBuilder();
int r;
try{
InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in);
while ((r = reader.read()) != -1) {
if(r=='+'){
list.add(builder.toString());
builder = new StringBuilder();
}
builder.append(r);
}
}catch (IOException ex){
ex.printStackTrace();
}
for(String a: list){
System.out.println(a);
}
}
Here is one way, caveat being you can't load more than the max int size (roughly one GB)
FileReader fr=null;
try {
File f=new File("your_file_path");
fr=new FileReader(f);
char[] chars=new char[(int)f.length()];
fr.read(chars);
String s=new String(chars);
//parse your string here
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
}
}
}
I am trying to create a split() method that reads a file, line by line, then separates the Strings and Integers into an array that is then written to another file. I have created an array to hold each String called list and one to hold the Integers called scores.
When I try to run my code, it reaches the second element in the list array which is surname = list[1] and then I get the error.
What I am trying to eventually do is split each element and get the average of the Integers so the original line of text would read Mildred Bush 45 65 45 67 65 and my new line of text would read Bush, Mildred: Final score is x.xx.
The error happens at line 7 surname = list[1];
My code:
public void splitTest()
{
String forename, surname, tempStr, InputFileName, OutputFileName;
tempStr = "";
String[] list = new String[6];
list = tempStr.split(" ");
forename = list[0];
surname = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
clrscr();
System.out.println("Please enter the name of the file that is to be READ (e.g. details.txt) : ");
InputFileName = Genio.getString();
System.out.println("Please enter the name of the file that is to be WRITTEN TO (e.g. newDetails.txt) : ");
OutputFileName = Genio.getString();
try {
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
outputStream = new FileOutputStream(OutputFileName);
printWriter = new PrintWriter(outputStream);
tempStr = bufferedReader.readLine();
while (tempStr != null) {
System.out.println(tempStr);
printWriter.write(tempStr+"\n");
tempStr = bufferedReader.readLine();
}
System.out.println("\n\nYOUR NEW FILE DATA IS DISPLAYED ABOVE!\n\n");
pressKey();
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
System.out.println("Sorry, there has been a problem opening or reading from the file");
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred when attempting to close the file");
}
}
if(printWriter != null) {
printWriter.close();
}
}
}
Where it says Genio, this a class that deals with user input.
You initialize the list array with
list = tempStr.split(" ");
The size of that array can be anything. It depends on the number of spaces in tempStr.
You have to check the length of list before accessing its elements.
If you expect the input to contain a certain number of parameters, add a check :
list = tempStr.split(" ");
int[] scores = new int[5];
if (list.length > 6) {
forename = list[0];
surname = list[1];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
}
This would prevent the exception. Of course, you have to decide how to handle the situation in which the condition is false.
EDIT :
tempStr = "";
This means there would be exactly one element in list. I'm assuming you meant to put some actual value in this variable.
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
}
}
Okay this is code and I need to somehow take a line from the textfile and transform into an array object. like p[0] = "asdasdasd"
public class Patient2 {
public static void main(String args[])
{
int field = 0;
String repeat = "n";
String repeat1 = "y";
Scanner keyIn = new Scanner(System.in);
// FILE I/O
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Patient.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
ArrayList<Patient1> patients=new ArrayList<Patient1>();
Patient1 p =new Patient1();
//set value to the patient object
patients.add(p);
System.out.println(p);
}
}
Instead of printing it to console you can add it to List<String>
List<String> lines = new ArrayList<String>();
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
lines.add(strLine)
}
Note: your code can be much cleaner, you can handle closing resources in finally
Just use an ArrayList<String> with add(strline); and use toArray(new String []) to get the array after input stream has been closed.
ArrayList<String> list = new ArrayList<String>();
...
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
...
String [] s = list.toArray(new String []);