目前我正在使用扫描仪/文件读取器并使用whilenextline.我认为这种方法效率不高.有没有其他方法来读取具有类似功能的文件?
public void Read(String file) {
Scanner sc = null;
try {
sc = new Scanner(new FileReader(file));
while (sc.hasNextLine()) {
String text = sc.nextLine();
String[] file_Array = text.split(" ", 3);
if (file_Array[0].equalsIgnoreCase("case")) {
//do something
} else if (file_Array[0].equalsIgnoreCase("object")) {
//do something
} else if (file_Array[0].equalsIgnoreCase("classes")) {
//do something
} else if (file_Array[0].equalsIgnoreCase("function")) {
//do something
}
else if (file_Array[0].equalsIgnoreCase("ignore")) {
//do something
}
else if (file_Array[0].equalsIgnoreCase("display")) {
//do something
}
}
} catch (FileNotFoundException e) {
System.out.println("Input file " …Run Code Online (Sandbox Code Playgroud) 我正在阅读文本文件中的200万行,如上一个问题中提到的 Java最快的方式来阅读200万行的文本文件
现在我将这些信息存储到HashMap中,我想通过TreeMap对其进行排序,因为我想使用ceilingkey.以下方法是否正确?
private HashMap<Integer, String> hMap = new HashMap();
private TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(hMap);
Run Code Online (Sandbox Code Playgroud) 我有一串国家缩写的注释,我想将它们分开,以便我可以识别每个缩写的国家.这样我将拥有String c = USA; 我将输出国家名称......
目前它没有c = USA但只有A
public class Example {
public static void main(String[] args) {
String x = "USAIND";
String c = "";
System.out.print("Country: ");
for (int i = 0; i < 3; i++) {
c = Character.toString(x.charAt(i));
System.out.print(c);
if (c.equals("USA")) {
System.out.println("United State of America");
}
}
System.out.println("");
System.out.print("Country: ");
for (int i = 3; i < 6; i++) {
c = Character.toString(x.charAt(i));
System.out.print(c);
if (c.equals("IND")) {
System.out.println("India");
}
}
System.out.println("");
}
}
Run Code Online (Sandbox Code Playgroud) 我写了以下代码,但是我需要跳过第一行,因为它是字段名称.我的文件是cart.csv.当代码读取第一行时,我将得到错误.
cart.csv
Number,Item,Quantity
1,Book,10
2,Fruit,14
3,Toy,2
Run Code Online (Sandbox Code Playgroud)
码
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] data = line.split(",");
String sql = "INSERT INTO DB (Number,Item,Quantity) values (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, data[0]);
pstmt.setString(2, data[1]);
pstmt.setString(3, data[2]);
pstmt.executeUpdate();
System.out.println("Upload Completed");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException ex) {
Logger.getLogger(POI.class.getName()).log(Level.SEVERE, null, ex);
}
Run Code Online (Sandbox Code Playgroud)