Move First Word to end of String Java - java

move keywords flagstop, wb, nb, sb, eb from start of the names to the end of the names
of the stops when reading the file
eg “WB HASTINGS ST FS HOLDOM AVE” becomes “HASTINGS ST FS HOLDOM AVE WB”.
So far I have gotten the code to read in the file as shown below, but im unsure how to move keyword of this string in array to end of string given the criteria shown above.
I need to be able to move first word in stops[2] if it is any of the above postcodes. Is there a way in JAVA to do this? Im thinking I need to make separate a function (moveFirstToLast) and call this in the main, but im having difficulty with this.
'''
String line = "";
try {
#SuppressWarnings("resource")
BufferedReader x = new BufferedReader(new FileReader("stops.txt"));
while((line = x.readLine()) != null)
{
String[] stops = line.split(",");
System.out.println("Stop name:" + stops[2]);
}
}
'''

Using a regex replacement:
String input = "WB HASTINGS ST FS HOLDOM AVE";
String output = input.replaceAll("(\\S+) (.*)$", "$2 $1");
System.out.println(output); // HASTINGS ST FS HOLDOM AVE WB

You can use String#split() to separate the first word from the rest of the string.
public moveFirstToLast(String stopName){
String [] temp = stopName.split(" ", 2);
return temp[1] + " " + temp[0];
}

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Sample_Two {
public static void main(String[] args) {
String line = "";
try {
#SuppressWarnings("resource")
BufferedReader x = new BufferedReader(new FileReader("stops.txt"));
while ((line = x.readLine()) != null) {
System.out.println("Actual line===>" + line);
var arr = line.split("\\s");
if (arr != null && arr.length > 0) {
System.out.println("Updated line===>" + line.substring(line.indexOf(" ")) +" "+ arr[0]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can try above code.
Why you are splitting through comma ",".
You need to split through space.
This will help you.

Related

Counting amount of times a mutation occurs in a .maf file

I'm trying to count the number of mutations in a MAF file. I originally wrote this code in python and it worked perfectly fine, but when I translated it to Java it stopped working. In the output file the number of mutations is always one. What am I doing wrong here?
package dev.suns.bioinformatics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
public class Main {
static String filePath = "C:/Users/Matthew/Bioinformatics/Data Files/DLBC.maf";
static String fileName = "DLBC_Info.txt";
public static void main(String[] args){
createFile(filePath, fileName);
}
public static void createFile(String filePath, String fileName){
BufferedReader br = null;
String line = "";
String delimiter = "\t";
String geneSymbol = "";
String newGene = "";
int count;
try {
PrintWriter writer = new PrintWriter(fileName);
br = new BufferedReader(new FileReader(filePath));
writer.println("Gene" + "\t" + "Mutations" + "\n");
br.readLine();
while ((line = br.readLine()) != null){
String[] splitFile = line.split(delimiter);
newGene = splitFile[0];
if(geneSymbol == ""){
geneSymbol = newGene;
}
else if(newGene == geneSymbol){
#This is here I am having trouble. I have this if-statement to check if the gene appears more than once in the .maf file, but nothing is ever entering this.
count++;
}
else{
count++;
writer.println(geneSymbol + "\t" + count + "\n");
geneSymbol = newGene;
count=0;
}
}
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is what the first few lines of the file look like
Gene Mutations
A1CF 1
A2M 1
A2M 1
A2ML1 1
A4GALT 1
AADAC 1
AADACL3 1
AAED1 1
AAGAB 1
AAGAB 1
AARD 1
AARS2 1
AARS2 1
AARS2 1
In java you need to compare strings using equals function. This should work-
else if(newGene.equals(geneSymbol)){
#This is here I am having trouble. I have this if-statement to check if the gene appears more than once in the .maf file, but nothing is ever entering this.
count++;
}
"==" checks for the reference. whether they are same string objects. In order to compare values of string you need to use equals() function.

Java - Reading from csv file getting null value

I am getting a null value when im reading from my teachers. csv file. Column 1 which is att[0] works but att[1] returns 3 null values.
My csv looks like this:
1, Mr Murphy
2, Mr Davis
3, Ms Simpson
Each on separate lines ie line 1 -> 1, Mr Murphy etc
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV
{
public static void main(String[] args)
{
//Input file which needs to be parsed
String readTeachers = "teacher.csv";
BufferedReader fileReader = null;
//Delimiter used in CSV file
final String DELIMITER = ",";
try
{
String line = "";
//String line = inFile.readLine();
//Create the file reader
fileReader = new BufferedReader(new FileReader(readTeachers));
int count=0;
String[] att = new String[10];
//Read the file line by line
while ((line = fileReader.readLine()) != null)
{
//Get all tokens available in line
String[] tokens = line.split(DELIMITER);
int i=0;
count++;
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break;
}
}
//System.out.println(count);
//System.out.println(att[1]);
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your issue here is that you have a break statement inside the for loop that exits the loop at the end of the first iteration. Therefore, you are only putting a value in the first index of your array. Take out that statement and it should be fine.
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break; // <---- ***take this out***
}

print a line that contains a specific pattern from a text-file in java

public class Auto
{
public static void main(String [] args) {
// The name of the file to open.
System.out.print("\nPlease enter TextfileName.txt : ");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.next();
int counter = 0;
//Reading filename.text from code
System.out.println("\nReading '"+fileName+"' from Java Code.\n");
//Date and time stamp for the program.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.print("Todays date: "+dateFormat.format(date)+"\n\n\n");
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
//-------------------------------------------------------TAB_1----------------------------------------------//
System.out.println("\t\t\t\t TAB_1[Date on]\n");
try {
// FileReader reads text files in the default encoding.
fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 1 || counter == 3 || counter == 9)
{
// print out the lines above that are found in the text
System.out.println(line);
System.out.println("----------");
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
// BufferedReader.close();
}
}
some matcher would help, but i`m not sure how it works
}}
The one i have above is working but i want to also find a specific string anywhere in the text-file and print that line
Just use the contains method of the String class to check for occurances of a substring inside a string.
while((line = bufferedReader.readLine()) != null) {
if (line.contains("some string") {
System.out.println(line);
System.out.println("----------");
}
}
If you wish to check multiple substrings and not just one then you should create a String array of all the substrings you want to look for and loop through them.
First add the following line at the beggining of the class :
public static final String[] listOfStrings = new String[] { "substring 0", "sub string 1" , "substring 2" };
Replace the substrings with your own values.
Then, loop through them to find matches:
while((line = bufferedReader.readLine()) != null) {
for (String match : listOfStrings) {
if (line.contains(match)) {
System.out.println(line);
System.out.println("----------");
break; // No need to continue after the first match
}
}
}

JAVA : file I/O

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();
}
}

Two problems with this java code, one fatal one not as fatal what are they?

Here is my code. This was a program I made for an interview, I was told the code had one fatal flaw, and one smaller problem. I could not find either. What is wrong with the program? I've tested it and it seems to work fine. I know the fileExists() method is kind of bad and need to do more checks... But other than that I am not sure what else could be wrong...
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//I chose to use this library since it offers a solution to performing operations on CSV files, better than one I can provide from scratch.
import au.com.bytecode.opencsv.CSVReader;
public class csv2xml {
//Main program loop
public static void main(String[] args) {
String csvFilename;
String xmlFilename;
ArrayList<ArrayList<String>> data; //Raw unformatted data
boolean exists;
String xml; //Formated XML data
do{
System.out.println("Enter file path: ");
csvFilename = getUserInput(); //Gets filename from user
exists = fileExists(csvFilename);
if(exists){ //Checks to see if file exists
data = readFile(csvFilename); //Reads in content from CSV file
xml = toXML(data);
xmlFilename = csvFilename.split("\\.")[0]+".xml"; //Gets part of the filename before the first .
writeToFile(xml,xmlFilename);
}
else
System.out.println("Invalid file name, use full file path.");
}while(!exists);
}
//Reads a line of input from the user
//Returns: String
public static String getUserInput(){
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
return input;
}
//Checks to see if the file exists
//Arguments: String (name of file)
//Returns Boolean, true if file exists, false if it does not exist.
public static boolean fileExists(String filename){
File file = new File(filename);
if (file.exists()){
System.out.println("File exists");
return true;
}
return false;
}
//Reads content of CSV file and returns all data in a 2D array list
//Arguments: String (file name)
//Returns: ArrayList<ArrayList<String>> (A 2D arraylist containing the data from the csv file in a table format)
public static ArrayList<ArrayList<String>> readFile(String filename){
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> currentRow;
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String [] nextLine = null; // nextLine[] is an array of values in the current line
try {
while ((nextLine = reader.readNext()) != null) {
currentRow = new ArrayList<String>();
for(String s: nextLine){ //Puts data into a row in an arraylist
currentRow.add(s);
}
data.add(currentRow); //Adds row into arraylist
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
//Inserts xml tags between the data segments,rows and columns
//Arguments: ArrayList<ArrayList<String>> (csv data)
//Returns: String (data with xml tags)
public static String toXML(ArrayList<ArrayList<String>> data){
String xml = "<?xml version= \"1.0\"?>";
for(int i = 0; i < data.size(); i++){
xml += "\n<row id=\""+i+"\">\n";
for(int z = 0; z < data.get(i).size(); z++){
xml += "<column id=\""+z+"\">\n";
xml += "\t<data>";
xml += data.get(i).get(z);
xml += "</data>";
xml += "\n</column>\n";
}
xml += "</row>";
}
return xml;
}
//Writes data in the filename specified
//Arguments: String (data to write), String (filename to write data to)
public static void writeToFile(String data,String filename){
try {
String fn = filename;
File file = new File(filename);
// if file doesnt exists, then create it
if (file.exists()) {
System.out.println("File already exists, overwrite?(y/n):");
if(getUserInput().toLowerCase().equals("n")){
do{
System.out.println("Enter new file name:");
filename = getUserInput()+".xml";
file = new File(filename);
}while(!isValidName(filename));
}
}
else{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
//Check files name to make sure it is valid (found in MSDN Documentation)
//Arguments: String (filename)
//Returns: Boolean (true if filename is valid false if invalid)
public static boolean isValidName(String text)
{
Pattern pattern = Pattern.compile(
"# Match a valid Windows filename (unspecified file system). \n" +
"^ # Anchor to start of string. \n" +
"(?! # Assert filename is not: CON, PRN, \n" +
" (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" +
" CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" +
" COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" +
" ) # LPT6, LPT7, LPT8, and LPT9... \n" +
" (?:\\.[^.]*)? # followed by optional extension \n" +
" $ # and end of string \n" +
") # End negative lookahead assertion. \n" +
"[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" +
"[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" +
"$ # Anchor to end of string. ",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}
}
Here is what I guess :
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String [] nextLine = null; // nextLine[] is an array of values in the current line
try {
while ((nextLine = reader.readNext()) != null) {
currentRow = new ArrayList<String>();
for(String s: nextLine){ //Puts data into a row in an arraylist
currentRow.add(s);
}
data.add(currentRow); //Adds row into arraylist
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So what happens if you do not initialize CSVreader ? The next block will throw a NullPointer Exception. You are not catching that one.
Also you are reading manually line by line when you can you simply use the library function.

Categories