So I'm trying to use a BufferedReader to split a text file into 2 different arrays, I've written some code but I'm not sure where to go from here.
I know how to populate an array, but i just cant seem to get the specific lines.
So, one array for NEW_OFFICE containing only the numbers, and one for MAIN_ADDRESS containing only the numbers below it.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}
This is the text file:
NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196
NEW_OFFICE always is the first line, and always has two lines below
it, the same goes for MAIN_ADDRESS it always has one line below it.
NEW_OFFICE & MAIN_ADDRESS can't appear more than once.
Based on your comment mentioned above, given below is the solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}
// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}
Output:
Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]
Notes:
\\s+ is for splitting the line on space(s).
Use try-with-resources syntax to simplify your code.
.split() does take a string, but it should be a regex, not the substring that you want to split it on. You want to change your code like this:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String read;
String office = "";
while ((read = in.readLine()) != null) {
if (read.contains("NEW_OFFICE")) {
office = "NEW_OFFICE";
} else if (read.contains("MAIN_ADDRESS")) {
office = "MAIN_ADDRESS";
} else {
System.out.println(office + " : " + read);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have also changed your try with try-with-resources so you don't have to worry about closing the resource.
I´d go with somethin like this.
Please be aware that I don´t have an IDE right now so this is basically pseudo code:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String line = null;
boolean isOffice = false;
ArrayList<double> officeInts = new ArrayList<double>();
ArrayList<double> addressInts = new ArrayList<double>();
while ((line = in.readLine()) != null) {
if (line.contains("NEW_OFFICE")) {
isOffice = true;
continue;
} else if (line.contains("MAIN_ADDRESS")) {
isOffice = false;
continue;
}
for(String s : line.split(" "){
double num = Double.parseDouble(s);
if(isOffice) {
officeInts.add(num);
} else {
addressInts.add(num);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
Related
I am trying to read a file called ecoli.txt, which contains the DNA sequence for ecoli, and store its contents into a string. I tried to print the string to test my code. However, when I run the program, there is no output. I am still new to java so I am sure there is an error in my code, I just need help finding it.
package codons;
import java.io.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader codons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_string = new StringBuilder();
String line = ecoli.readLine();
while(line != null);
{
dna_string.append(line);
line = ecoli.readLine();
}
String string = new String(dna_string);
System.out.println(string);
ecoli.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
edit:
I was still having trouble getting the program to work the way I wanted it to so I attempted to complete writing the rest of what I wanted in the program and I am still not getting any output. Anyway, this is where I am at now:
package codons;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader filecodons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_sb = new StringBuilder();
String line = ecoli.readLine();
while(line != null)
{
dna_sb.append(line);
line = ecoli.readLine();
}
String dna_string = new String(dna_sb);
ecoli.close();
BufferedReader codons = new BufferedReader(filecodons);
StringBuilder codon_sb = new StringBuilder();
String codon = codons.readLine();
while(codon != null)
{
codon_sb.append(codon);
line = codons.readLine();
}
String codon_string = new String(codon_sb);
codons.close();
for(int x = 0; x <= codon_sb.length(); x++)
{
int count = 0;
String codon_ss = new String(codon_string.substring(x, x+3));
for(int i = 0; i <= dna_sb.length(); i++)
{
String dna_ss = new String(dna_string.substring(i, i+3));
int result = codon_ss.compareTo(dna_ss);
if(result == 0)
{
count += 1;
}
}
System.out.print("The codon '");
System.out.print(codon_ss);
System.out.print("'is in the dna sequence");
System.out.print(count);
System.out.println("times.");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Remove the ; after while(line != null), it causes an infinite loop instead of executing the next instructions.
The reason is explained here: Effect of semicolon after 'for' loop (the question is about the C language, but it is equivalent in Java).
I have got two text files with data in the following format
data.txt file as following format
A 10
B 20
C 15
data1.txt file is in format (start node,end node, distance):
A B 5
A C 10
B C 20
I am trying to implement a search strategy, for that I need to load the data from data.txt and ONLY the start node and end node from data1.txt (i.e. I dont need the distance). I need to store this information in a stack as I think it would be a best data structure for implementing greedy search.
Actually I am not sure how to get started with file I/O to read these files and store them in array to implement greedy search. So I would highly appreciate any starting idea on how to proceed.
I am new to this, so please bear with me. Any help is much appreciated. Thanks.
EDIT:
Here is what I have got till now
String heuristic_file = "data.txt";
try
{
FileReader inputHeuristic = new FileReader(heuristic_file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
while ((line = bufferReader.readLine()) != null)
{
System.out.println(line);
}
bufferReader.close();
} catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
My approach, doesn't differ fundamentally from the others. Please regard the try/catch/finally blocks. Always put the closing statements into the finally block, so the opened file is guaranteed to be closed, even if an exception was thrown while reading the file.
The part between the two //[...] could surely be done more efficient. Maybe reading the whole file in one take and then parsing the text backwards and searching for a line-break? Maybe a Stream-API supports to set the reading position. I honestly don't know. I didn't need that, up to now.
I chose to use the verbose initialization of the BufferedReader, because then you can specify the expected encoding of the file. In your case it doesn't matter, since your files do not contain symbols out of the standard ASCII range, but I believe it's a semi-best-practice.
Before you ask: r.close() takes care of closing the underlying InputStreamReader and FileInputStream in the right order, till all readers and streams are closed.
public static void readDataFile(String dir, String file1, String file2)
throws IOException
{
File datafile1 = new File(dir, file1);
File datafile2 = new File(dir, file2);
if (datafile1.exists())
{
BufferedReader r = null;
try
{
r = new BufferedReader(
new InputStreamReader(
new FileInputStream(datafile1),
"UTF-8"
)
);
String row;
Stack<Object[]> s = new Stack<Object[]>();
String[] pair;
Integer datapoint;
while((row = r.readLine()) != null)
{
if (row != null && row.trim().length() > 0)
{
// You could use " " instead of "\\s"
// but the latter regular expression
// shorthand-character-class will
// split the row on tab-symbols, too
pair = row.split("\\s");
if (pair != null && pair.length == 2)
{
datapoint = null;
try
{
datapoint = Integer.parseInt(pair[1], 10);
}
catch(NumberFormatException f) { }
// Later you can validate datapairs
// by using
// if (s.pop()[1] != null)
s.add(new Object[] { pair[0], datapoint});
}
}
}
}
catch (UnsupportedEncodingException e1) { }
catch (FileNotFoundException e2) { }
catch (IOException e3) { }
finally
{
if (r != null) r.close();
}
}
// Do something similar with datafile2
if (datafile2.exists())
{
// [...do the same as in the first try/catch block...]
String firstrow = null, lastrow = null;
String row = null;
int i = 0;
do
{
lastrow = row;
row = r.readLine();
if (i == 0)
firstrow = row;
i++;
} while(row != null);
// [...parse firstrow and lastrow into a datastructure...]
}
}
use split
while ((line = bufferReader.readLine()) != null)
{
String[] tokens = line.split(" ");
System.out.println(line + " -> [" + tokens[0] + "]" + "[" + tokens[1] + "][" + tokens[2] + "]");
}
if you must have this in an array you can use the following:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class NodeTest {
public static void main(String[] args) throws ParseException {
try {
File first = new File("data.txt");
File second = new File("data1.txt");
Node[] nodes1 = getNodes(first);
Node[] nodes2 = getNodes(second);
print(nodes1);
print(nodes2);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public static final void print(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}
public static final Node[] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List<Node> list = new ArrayList<Node>();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]);
}
}
class Node {
String start;
String end;
public Node(String start, String end){
this.start = start;
this.end = end;
}
public String toString() {
return "[" + start + "][" + end + "]";
}
}
Something like this?
HashSet<String> nodes = new HashSet<String>();
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
nodes.add(l[0]);
line = br.readLine();
}
}
try(BufferedReader br = new BufferedReader(new FileReader("data1.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
if (nodes.contains(l[0]) || nodes.contains(l[1]))
// Do whatever you want ...
line = br.readLine();
}
}
I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.
I have a program which reads a file I can change the content of this file and after that it's written to another file. The input file looks like this: http://gyazo.com/4ee1ade01378238e2c765e593712de7f and the output has to look like this http://gyazo.com/5a5bfd00123df9d7791a74b4e77f6c10 my current output is http://gyazo.com/87a83f4c6d48aebda3d11060ebad66c2 so how to change my code that it's starts a new line after 12 characters? Also I want to delete the last !.
public class readFile {
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
//buf.append(System.getProperty("line.separator"));
}
/* start with a new line if the line length is bigger than 12 - in progress*/
/* I know this if doesn't work but how to fix it? */
if (buf.length()>12){
buf.append(System.getProperty("line.separator"));
}
/* if a * is followed by * change them to a !*/
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
//buf.deleteCharAt(buf.length()-1);
}
// get last character from stringbuilder and delete
//buf.deleteCharAt(buf.length()-1);
}
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/test.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Update the code in which while reading the file you will take the decision :
int sevenCount = 0;
int fourteenCount = 0;
int data = 0;
while ((data = reader.read()) != -1) {
sevenCount++;
fourteenCount++;
if(sevenCount==7)
{
buf.append("-"); // append - at every 7th character
sevenCount = 0;
}
if(fourteenCount==14)
{
buf.append("\n"); // change line after evrry 14th character
fourteenCount = 0;
}
if(((char)data) == '*')
{
char c = '!'; //Change the code when char contain *
data = (int)c;
}
else
{
buf.append((char)data);
}
}
If you want to insert a newline in a string every 12 chars:
str = str.replaceAll(".{12}", "$0\n");
I got this far, but it seems that buffer won't take arrays, because first I had it this way
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
// System.out.println (strLine);
String Record = strLine;
String delims = "[,]";
String[] LineItem = Record.split(delims);
//for (int i = 0; i < LineItem.length; i++)
for (int i = 0; i == 7; i++)
{
System.out.print(LineItem[i]);
}
now I leave at this, because it's reading but not taking out commas.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class mainPro1test {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\2010_Transactions.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
String Record = text;
String delims = "[,]";
String[] LineItem = Record.split(delims);
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
of how it should look like
input
Sell,400,IWM ,7/6/2010,62.481125,24988.02,4.43
Sell,400,IWM ,7/6/2010,62.51,24999.57,4.43
output
Sell 400 IWM 7/6/2010 62.481125 24988.02 4.43
Sell 400 IWM 7/6/2010 62.51 24999.57 4.43
If you only want to remove commas from a String, you can use String.replaceAll(",","");
If you want to replace them by spaces, use String.replaceAll(","," "):
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.
Easier is to define a new InputStream that just removes the commas...
class CommaRemovingStream extends InputStream {
private final InputStream underlyingStream;
// Constructor
#Override public int read() throws IOException {
int next;
while (true) {
next = underlyingStream.read();
if (next != ',') {
return next;
}
}
}
}
Now you can read the file without commas:
InputStream noCommasStream = new CommaRemovingStream(new FileInputStream(file));