cht電腦資訊Language
adm Find login register

C vs Java (fscan vs …)

eliu

joined: 2007-08-09
posted: 11480
promoted: 617
bookmarked: 187
新竹, 台灣
1subject: C vs Java (fscan vs …)Promote 0 Bookmark 02012-01-13quote  

我不怎麼喜歡 java,我覺得 C 很多方面比 java 簡單又直接。最近因為在 Android 開發 AP,不得不用 java

來看一個很簡單的 example

我想要把 a.txt 依欄位一行一行讀進去

在 C 我們可以用 fscanf,輕鬆搞定,也很容易看懂。

#include <stdio.h>

FILE *fp;
char a[80],b[80],c[80];

if (fp=fopen("a.txt", "r"))==NULL)
   die("cannot open");

while (!feof(fp)) {
   fscanf(fp, "%s %s %s", a,b,c); 
}

fclose(fp)


在 java 很麻煩

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.util.StringTokenizer;
import java.io.DataInputStream;

try{
  FileInputStream fstream = new FileInputStream("a.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine,a,b,c;
  while ((strLine = br.readLine()) != null) {
    System.out.println (strLine);
    StringTokenizer st = new StringTokenizer(strLine);
    a=st.nextToken();
    b=st.nextToken(); 
    c=st.nextToken(); 
  }

  in.close();
} catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
}

edited: 3
Guest
joined: 2010-06-05
posted: 57
promoted: 2
bookmarked:
2subject: Promote 0 Bookmark 02012-01-12quote  

使用Java在IO的部分我也覺得實在是太麻煩了,尤其是習慣了在腳本語言的便利性後。最近有在想利用時間學groovy來簡化一些令人感到厭煩的步驟。

sendxp

joined: 2009-06-24
posted: 101
promoted: 23
bookmarked: 6
地球
3subject: Promote 0 Bookmark 02012-01-13quote  

Maybe can try golang or Scala...

eliu

joined: 2007-08-09
posted: 11480
promoted: 617
bookmarked: 187
新竹, 台灣
4subject: Promote 0 Bookmark 02012-01-13quote  

除非 android 有built-in,否則接受度應該是很低?

cht電腦資訊Language
adm Find login register
views:12625