How to Check if File Exists in C Sharp/C# ?

Hi,

Use the following simple lines of code to check whether a particular file exists or not using C#/C Sharp.

using System;
using System.IO;

static class MainClass
{
    static void Main(string[] args)
    {
           Console.WriteLine(File.Exists("c:yourFile.txt"));
    }
}

It will return either True or False depending on whether your file exists or not.
:)

Conversion from String to Double using C#

Hi,

Sometimes you may need to convert string to double using C#, see the following lines of code to see how you could do it.

class MainClass
{
  static void Main()
  {

    string myString = " 3.14159";
    double myValue= System.Convert.ToDouble(myString );

  }
}

:)

Get characters in a string – C Sharp/C#

Hi,

Sometimes you may need to get all the characters in a string using C Sharp/C#. The following code gives you an example of how to get or display all the characters of a given string.

using System;

class MainClass
{

  public static void Main()
  {
    string sampleString= "I Love Coding";


    for (int num = 0; num < sampleString.Length; num++)
    {
      Console.WriteLine("sampleString[" + num + "] = " + sampleString[num]);
    }

  }

}

Output:
sampleString[0] = I
sampleString[1] =
sampleString[2] = L
sampleString[3] = o
sampleString[4] = v
sampleString[5] = e
sampleString[6] =
sampleString[7] = C
sampleString[8] = o
sampleString[9] = d
sampleString[10] = i
sampleString[11] = n
sampleString[12] = g
:)

Java check memory Allocation

class test
{
	public static void main(String args[])
	{
			Runtime r = Runtime.getRuntime();
			long mem1, mem2;
			Integer someints[] = new Integer[1000];
			System.out.println("Total memory is: " +r.totalMemory());
			mem1 = r.freeMemory();
			System.out.println("Initial free memory: " + mem1);
			r.gc();
			mem1 = r.freeMemory();
			System.out.println("Free memory after garbage collection: "+ mem1);

			for(int i=0; i<1000; i++)
				someints[i] = new Integer(i); // allocate integers
			mem2 = r.freeMemory();

			System.out.println("Free memory after allocation: "	+ mem2);
			System.out.println("Memory used by allocation: "+ (mem1-mem2));

			// 	discard Integers
			for(int i=0; i<1000; i++) someints[i] = null;
				r.gc(); // request garbage collection

			mem2 = r.freeMemory();
			System.out.println("Free memory after collecting" +" discarded Integers: " + mem2);
	}
}

When run the code the output will be similar to this

Total memory is: 5177344
Initial free memory: 4986744
Free memory after garbage collection: 5063784
Free memory after allocation: 5045296
Memory used by allocation: 18488
Free memory after collecting discarded Integers: 5063784

How to Convert a string to date in JAVA ?

Hi,

For converting string to a date in JAVA use the following code.

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

  public static void main(String[] args) throws Exception {

    SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");

    Date dateToday = dateFormat.parse("25/06/2011");

    System.out.println(myDateFormat.format(dateToday));

  }
}

:)

Hi,

Use the following simple lines of code to check whether a particular file exists or not using C#/C Sharp.

using System;
using System.IO;

static class MainClass
{
    static void Main(string[] args)
    {
           Console.WriteLine(File.Exists(&quot;c:yourFile.txt&quot;));
    }
}

It will return either True or False depending on whether your file exists or not.
:)

Single Selection ListView in android

Hello all…..

In today’s post I will show you how to create a single selection list in android.

Here is the main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
     <ListView
		 	android:id="@android:id/list"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:dividerHeight="1px"
			android:padding="5dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginLeft="10dip"
		    android:layout_marginRight="10dip"
		    android:layout_marginBottom="10dip"
		    android:layout_weight="1"/>

</LinearLayout>

Now this line in the java file creates the single choice.

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_single_choice,
android.R.id.text1, names));

Now this is the full java code

package com.coderzheaven.pack;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListView1 extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String[] names = new String[] { "Android", "Windows7", "Symbian", "iPhone",
        		"Android", "Windows7", "Symbian", "iPhone",
        		"Android", "Windows7", "Symbian", "iPhone" };
		setListAdapter(new ArrayAdapter<String>(this,
					   android.R.layout.simple_list_item_single_choice,
					   android.R.id.text1, names));
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    }
}

Single Choice ListView

Single Selection ListView in android

How to replace a substring in C Sharp/C# ?

Hi,

For replacing a substring in C Sharp/C#, use the following lines of code.

using System;

  class Class1
  {
    static void Main(string[] args)
    {
            string newStr = "Heaven";

            string finalStr = "CoderzWorld";

            finalStr = finalStr.Replace( "World", newStr);

            Console.WriteLine( finalStr);

    }
    }

How to create a new file using JAVA ?

Hi,

For creating a new file using JAVA, use the following code.

import java.io.File;
public class MainClass {

  public static void main(String[] a)throws Exception {

    File myFile = new File("c:\temp\newText.txt");

    myFile.createNewFile();

  }

}

Exception Handling – Divide by Zero – Java Example

Hi,

Given below is a code snippet which will demonstrate an exception handling in Java with Divide by zero error.

public class MainClass {
  public static void main(String args[]) {

    int urAns, urDiv;

    try {

      urDiv = 0;
      urAns = 25 / urDiv;

      System.out.println("Do you really think this will print out? No! It won't!");

    }

    catch (ArithmeticException e) {

      System.out.println("Division by zero not Possible!");

    }

    System.out.println("This will print out after Exception Handling");
  }

}

:)

Simple String Concatenation Example in JAVA

Hi,

Given below is a simple concatenation example in JAVA where two strings are joined together to form a single string.

public class MainClass {

  public static void main(String[] arg) {

    String yourString = "Coderz" + "Heaven";

    System.out.println(yourString);

  }

}

And…the output will be.. “CoderzHeaven”
:)

How to search for substring from a string in JAVA ?

Hi,

For searching for a particular substring from a starting index of a string and get the starting index of it in JAVA, use the following sample of code.


public class MainClass{

  public static void main(String[] arg){

    String myStr = "coderzco";

    int begIndex= 2;

    int myIndex= 0;

    myIndex = str.indexOf("co", begIndex);

    System.out.println(myIndex);
  }

}

It will print out the starting index of the substring ‘co’ (the second ‘co’), that is 6.

:)

How to search for characters from strings in JAVA ?

Hi,

For searching for a particular character from a string and getting the index of that particular character, use the following code.


public class MainClass{

  public static void main(String[] arg){

    String myStr = "Coderz";

    int strIndex = 0;
    strIndex = myStr.indexOf('o');

    System.out.println(strIndex);
  }

}

It will print out the index of ‘o’, that’s 1.
:)

Sort elements in a String Array – C Sharp / C#

Hi,

In order to sort the elements in a string array in C Sharp/C#, we use the sort() method. Given below is a simple example using sort() method to sort the elements in a string array.

using System;

class MainClass
{

  public static void Main()
  {

    string[] urStringArray = {"xylo", "apple", "zeebra", "coderz", "heaven123", "heaven777"};
    Array.Sort(urStringArray );
    Console.WriteLine("Sorted string Array:");
    for (int i = 0; i < urStringArray.Length; i++)
    {
      Console.WriteLine("urStringArray[" + i + "] = " + urStringArray[i]);
    }
  }

}

It will print out,
Sorted string Array:
urStringArray[0] = apple
urStringArray[1] = coderz
urStringArray[2] = heaven123
urStringArray[3] = heaven777
urStringArray[4] = xylo
urStringArray[5] = zeebra
:)

Program for Palindrome checking in C Sharp/C#

Hi,

Sometimes you need to check for whether the given string is Palindrome or not. Given below is a sample code to check whether the given string is Palindrome or not using C Sharp/C#.

class Palindrome
{
  static void Main()
  {
      string checkStr, sampleStr;
      char[] temp;

      System.Console.Write("Enter your String: ");

      sampleStr = System.Console.ReadLine();

      checkStr = sampleStr.Replace(" ", "");

      checkStr = checkStr.ToLower();

      temp = checkStr.ToCharArray();

      System.Array.Reverse(temp);

      if(checkStr== new string(temp))
      {
          System.Console.WriteLine(""{0}" is a palindrome.",sampleStr);
      }

      else
      {
          System.Console.WriteLine(""{0}" is NOT a palindrome.",sampleStr);
      }

  }
}

:)

Copy a file in C Sharp/C# without using FileInfo

Hi,

We have discussed here copying a file using FileInfo. Now we are going to see how we can do the same without using FileInfo in C Sharp/C#.

using System;
using System.IO;

class MainClass {
  public static void Main(string[] args) {

    int i;
    FileStream fileIn;
    FileStream fileOut;

    try {
      fileIn = new FileStream("opFile.txt", FileMode.Open);
    }
    catch(FileNotFoundException exc) {
      Console.WriteLine(exc.Message + "nFile Not Found");
      return;
    }

    try {
      fileOut = new FileStream("clFile.txt", FileMode.Create);
    }
    catch(IOException exc) {
      Console.WriteLine(exc.Message + "nError Opening File");
      return;
    }

    try {
      do {
        i = fileIn.ReadByte();
        if(i != -1)
           fileOut.WriteByte((byte)i);
      } while(i != -1);
    }
    catch(IOException exc) {
      Console.WriteLine(exc.Message + "Error");
    }

    fileIn.Close();
    fileOut.Close();
  }
}

Copying a file using FileInfo – C Sharp/C#

Hi,

For copying a file using FileInfo in C Sharp/C#, use the following code. For copying a file without using file info check the example given here.

using System;
using System.IO;

public class MainClass
{
  static void Main(string[] args)
  {

    FileInfo testFile = new FileInfo(@"c:NewWorkstestOld.txt");

    testFile.Create();

    testFile.CopyTo(@"c:NewProjtestNew.txt");

  }
}

:)

C Sharp/C# – Read a complete text file

Hi,

Use the following code example to read a complete text file using C Sharp/C#.

using System;
using System.Data;
using System.IO;



class Class1{

  static void Main(string[] args){

      StreamReader sampleStreaming= new StreamReader("trialText.txt");

      Console.WriteLine(sampleStreaming.ReadToEnd());

      sampleStreaming.Close();
    }
}
 :) 


How to split a String in ANDROID?


Hi all…..
Splitting a string in android is really easy.checkout the following snippet.

package com.coderzheaven;

import android.app.Activity;
import android.os.Bundle;

public class SplitStringDemo extends Activity {
    String str = "India, USA, Japan, Russia, France";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String arr[] = str.split(",");
        for(int i = 0; i < arr.length; i++){
        	System.out.println("arr["+i+"] = " + arr[i].trim());
        }
    }
}

Check the Logcat for output.
Note: Make sure to put the escape character before the delimiter for splitting,otherwise the output may be each character.

C Sharp/C# – String Uppercase/Lowercase Conversion

Hi,

It will be very useful to know how you can convert a given string into uppercase or lowercase using program.
We are going to show you , how to convert a given string into uppercase or lowercase using C Sharp/C#. See the example given below.

using System;

class MainClass {
  public static void Main() {

    string sampleString = "CoDeRzHeAvEn";

    string strLwrCase = sampleString .ToLower();
    string strUprCase =  sampleString .ToUpper();

    Console.WriteLine("Lowercase of sampleString :n " +  strLwrCase );
    Console.WriteLine("Uppercase of sampleString :n " +  strUprCase );

  }
}

Output :
Lowercase of sampleString :
coderzheaven
Uppercase of sampleString :
CODERZHEAVEN
:)

Compare two strings in C Sharp/C# – Case Insensitive

Hi,

Sometimes you may need to check whether two strings are equal or not equal by checking case insensitive. See the example below to see how to achieve the same using C Sharp /C#.

using System;

class MainClass {
  public static void Main() {

    string strOne = "heaven";

    string strTwo = "HEAVEN";

    if(String.Compare(strOne , strTwo , true) == 0)
      Console.WriteLine(strOne + " and " + strTwo + " are equal - Case Insensitive!");

    else
      Console.WriteLine(strOne + " and " + strTwo + " are not equal - Case Insensitive!");

  }
}

Output : heaven and HEAVEN are equal – Case Insensitive!
:)

Get files from a directory – C#/C Sharp

Hi,

Sometimes you may need to get the files from a specified directory using C# / C Sharp. See the sample code on how it works.

using System;
using System.IO;

class MainClass
{
  public static void Main()
  {
    string[] yourFiles = Directory.GetFiles("c:");

    foreach (string fNames in yourFiles)

      Console.WriteLine(fNames);
  }

}

This code will get you files from the root directory.
:)

C#/C Sharp – Delete file in a folder

Hi,

Let’s see a simple example of deleting a file in a folder using c#.

using System;
using System.IO;

public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo sampleFile= new FileInfo(@"c:SamplestestFile.txt");

    sampleFile.Create();

    sampleFile.Delete();

  }
}

sampleFile.Create() will create the file in the specified folder.
sampleFile.Delete() will delete the file in the specified folder.
:)

How to create a text file in C# ?

Hi,

How can you create a text file in C# and write to it? Sometimes you may need to create a text file using C sharp program. Here is how you can do that.

using System;
using System.IO;

class MainClass
{
  static void Main(string[] args)
  {
    StreamWriter yourStream= null;
    string yourString= "I Love Coderz Heaven!";

    try
    {
      yourStream = File.CreateText("testFile.txt");
      yourStream.Write(yourString);
    }
    catch (IOException e)
    {
      Console.WriteLine(e);
    }
    catch (Exception e)
    {
      Console.WriteLine(e);
    }
    finally
    {
      if (yourStream!= null)
      {
          yourStream.Close();
      }
    }
  }
}

:)

Accessing all items of an Array in C#

Hi,

In order to access all the items of an array in C#, use the following lines of code. We are using foreach loop to access all the elements of an array in C#.

using System;

class MainClass
{
    public static void Main()
    {
        string myString = "Apple Ball Cat";
        char[] separator = {' '};
        string[] spellArr= myString .Split(separator);

        foreach (object chk in spellArr)
           Console.WriteLine("Spell: {0}", chk );
    }
}

It will print out,
Spell: Apple
Spell: Ball
Spell: Cat
:)