Reading a text file with Java

February 20th, 2010

Recently I regularly use Java in some classes and my research. In particular, I often implement a similar code to read a text file for the purpose of some text processing. So I will attach the trivial code to this post for future reference. I confirmed that it works with Java 1.6.0_16.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

class SomeClass {
    public static void readFromFile(String filename) {
        BufferedReader fin = null;

        try {
            fin = new BufferedReader(new FileReader(filename));
            String line = null;
            while ((line = fin.readLine()) != null) {
                // Do something.
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fin != null) fin.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        readFromFile("sample.txt");
    }
}

Incidentally I have used BufferedReader rather than BufferedInputStream simply because BufferedReader is more suitable to the text processing that I need to do right now.

CSV to HTML converter

February 13th, 2010

I have spent some time implementing a small script with Python 2.6.2 to help my trivial work: concerting CSV to HTML (more precisely a CSV file to an HTML table). The CSV format for its input depends on what the csv module in Python specifies. The code is pretty straightforward:

#!/usr/bin/python

# csv2html.py
# CSV to HTML Converter

import csv
import sys

table_indent_num = 2
tr_indent_num = 4
td_indent_num = 6
white_space = " "

def main():
    csv_reader = csv.reader(open(sys.argv[1]))
    table_indent = white_space * table_indent_num
    tr_indent = white_space * tr_indent_num
    td_indent = white_space * td_indent_num

    print table_indent + "<table>"
    for i, row in enumerate(csv_reader):
        print tr_indent + "<tr>"

        # Uncomment the following two lines if you don't
        # want a column for indexes
        if i == 0: print td_indent + "<th>#</th>"
        else: print td_indent + "<td>" + str(i) + "</td>"

        # Assume that the first line is a header
        for column in row:
            if i == 0: print td_indent + "<th>" + column + "</th>"
            else: print td_indent + "<td>" + column + "</td>"

        print tr_indent + "</tr>"

    print table_indent + "</table>"

if __name__ == "__main__":
    argn = len(sys.argv)
    if argn != 2:
        print "Usage: python csv2html.py <CSV file>"
        exit(1)

    main()

An example of usage is as follows:

$ more sample.csv
title1,title2,title3
"test11",test12,test13
test21,"test,22",test23
$ python csv2html.py sample.csv > sample.html
$ more sample.html
  <table>
    <tr>
      <th>#</th>
      <th>title1</th>
      <th>title2</th>
      <th>title3</th>
    </tr>
    <tr>
      <td>1</td>
      <td>test11</td>
      <td>test12</td>
      <td>test13</td>
    </tr>
    <tr>
      <td>2</td>
      <td>test21</td>
      <td>test,22</td>
      <td>test23</td>
    </tr>
  </table>

Research methods in computer science

December 27th, 2009

During this winter break, I have been reading two books on doing research and publishing papers besides some textbooks for my classes next quarter. One book is Wayne C. Booth, Gregory G. Colomb, and Joseph M. Williams, The Craft of Research (3rd Edition), and the other is Robert A. Day and Barbara Gastel, How to Write and Publish a Scientific Paper (6th Edition). Though I have published a few papers so far, these books are of benefit to me in that I can regain an appreciation of appropriate ways of research.

When reading these books, I came to think of research methods particularly in the field of my major, computer science. Probably the only way to truly acquire the methods is to go through several years of actual research in computer science, but it is good to know some methodologies that are systematized to some extent. I found out about useful information on Dr. Vasant Honavar’s website: Graduate Research, Writing, and Careers in Computer Science. This web page contains a whole bunch of helpful links over various topics for computer science graduate students like me. I would be appreciate if you would be willing to leave your comments about other information on these topics.

My first Thanksgiving Day

November 27th, 2009

Today was my first Thanksgiving Day. The Stanford Graduate Student Council provided free Thanksgiving dinner, and I was happy to join the event. Of course, this was the first time for me to eat traditional Thanksgiving dishes such as turkey and pumpkin pie, but I liked them. It seemed like a number of first-year international students joined the event, including me. I got to know some students around me, and enjoyed a little chat with them. Since my last two months were really hectic, this event was a good relaxing time for me.

My classes and homework

October 24th, 2009

My classes started late last month. It is approximately seven years since I took regular classes at the University of Tokyo. There is a substantial difference in the amount of homework assignments between the two, although I knew this before taking classes. Sometimes they are really hard, but also valuable intellectual excitement.

Japanese cuisine in California

September 10th, 2009

The other day I eventually missed Japanese cuisine because I hadn’t eaten any Japanese food since I entered the United States on July 26. So when I fortunately got some help to go to the Japantown in San Jose last Saturday, I was happy to purchase some Japanese food and enjoy tofu cuisine in a restaurant there.

On the following day, I cooked rice and pacific sauries myself. They are typical Japanese autumnal fish called “sanma” in Japan. I was really astonished at the taste of the rice because it was exactly the same as the one in Japan. This is in part because of my Zojiruji rice cooker which I bought online after arriving here, but probably it depends greatly on the result of some breed improvement in Californian rice. My roommate and his friends were also pleased with my cooking. Here is a picture of the cooking:

I know that once my classes start on September 21, I will be so busy that I may not make much time to cook my own food. I, however, would like to continue to do so as far as possible because basically I like eating at home and believe that Japanese food is the secret of the longevity of Japanese people.

My life in Palo Alto

September 3rd, 2009

I have lived in graduate housing on campus at Stanford University since the end of last month, and enjoyed the process of organizing my life here little by little. Usually I get up in the morning, and study English and computer science, and cook some simple dishes, and sometimes go to some stores around campus by bike. Of course, I have been doing a range of things besides these to settle in this place, and take care of some administrative things for the university, and prepare for my study and so on. Last night I enjoyed chatting with my family in Tokyo on Skype, and was amazed at their technology which offered high speech quality and little time difference in our speeches between California and Tokyo.

I recently noticed that some people around Stanford University are very active. While riding my bike on and off campus, I always see several people running or riding their bikes just for exercise. Stanford is teeming with natural treasures such as a lake, trees, birds and even squirrels, and has pedestrian-and-bike-friendly campus on top of that, so all those people probably find pleasure in their daily exercise. When I have more free time someday, I would like to enjoy exercise just like them.

Arrival at Stanford University

August 15th, 2009

Yesterday I left UC Berkeley, got on the BART and then the Caltrain, and arrived at Stanford University some time after noon. This move was a short trip for around three hours, but it really exhausted me to take several suitcases. In addition, some offices were closed because my arrival was on Friday afternoon, so I have not yet proceeded with actual preparation, such as getting my student ID card and opening a bank account. Currently, I am staying in on-campus housing for undergraduates as short-term graduate housing. And the other day I was glad to receive a notification purporting that I had been assigned to on-campus housing for graduate students for 2009-2010.

What I was particularly impressed in the move above is that some people around Stanford University kindly volunteered to show me their detailed maps, tell me the best way to my destination, and even give me a ride to my house on campus, although I did not ask them at all. I don’t know why they were so obliging, but it might have something to do with spirit of international volunteerism which has taken root in this country.

Looking back, I have been here around one year and nine months after I made a decision to apply to graduate schools in the United States in November 2007. However, this is just my first step at Stanford University. Starting is of considerable importance to everything, and I will do the best possible to set up my new life, study English and computer science and so forth during the month before my classes start.

My life in Berkeley

August 9th, 2009

Approximately two weeks have passed since I arrived at UC Berkeley, and I really feel how fast the time goes. I currently live in the International House at UC Berkeley and enjoy my life here. The Bay Area, including Berkeley, has such comfortable weather that I don’t need any help of air conditioners even in the summer months. I cannot get this comfort in Tokyo. And some people in Berkeley have very kind hearts. For example, when I was looking for an office and opening up my map on the street on campus, an elderly man volunteered to tell me the way to the office, although I didn’t ask him to do so.

I will leave Berkeley in a week, but would like to have more good memories of it. Below are the pictures that I took at UC Berkeley yesterday.


This is an entrance of Soda Hall, the building of the Computer Science Division.


These are some objects for display at the Soda Hall. The interesting ones on the right side were created for Geometric Modeling.


This is a small animal on campus which delighted me with its quick movements when I was taking a walk.

Arrival at UC Berkeley

July 29th, 2009

After a long flight from Japan, I arrived at UC Berkeley three days ago. I have a lot of things which I want to write about right now, but I have been very busy because my classes have given us many homework assignments. So that’s all for today, and I will write something later on about UC Berkeley, the programs in which I am participating, and so forth.