2017-02-07 39 views
1

我在一個項目中工作,我想要一些幫助。將字符串從字符串複製到字符串

因此,這裏是我的測試代碼:

package test; 

import java.io.*; 

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

     // The name of the file to open. 
     String fileName = "C:\\Users\\karlk\\workspace\\Work\\src\\test\\tempx.txt"; 
     // This will reference one line at a time 
     String line = null; 

     try { 
      // FileReader reads text files in the default encoding. 
      FileReader fileReader = 
       new FileReader(fileName); 

      // Always wrap FileReader in BufferedReader. 
      BufferedReader bufferedReader = 
       new BufferedReader(fileReader); 

      while((line = bufferedReader.readLine()) != null) { 
       System.out.println(line); 
      } 

      // Always close files. 
      bufferedReader.close();   
     } 
     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(); 
     } 
    } 
} 

tempx.txt

Karlken:Java:Male 

這是我簡單的問題

1)我想在一個名爲字符串寫在':'(Karlken)之前命名第一個單詞,在另一個字符串(Java)中':'之後的第二個單詞,以及最後,再次在另一個字符串中我想寫「男」,我該怎麼辦?

+2

'line.split(「:」)' – shmosel

+0

您的第三個字符串混淆。您不只是指: String male =「male」; 是嗎? –

+0

String string =「C:\\ Users \\ karlk \\ workspace \\ Work \\ src \\ test \\ tempx.txt」; String [] parts = string.split(「:」); String part1 = parts [0]; String part2 = parts [1]; –

回答

0

您可以使用掃描儀用於此目的:

public static void main(String[] args){ 
    String fileName = "C:\\Users\\karlk\\workspace\\Work\\src\\test\\tempx.txt"; 

    try(Scanner scanner = new Scanner(new File(fileName))){ 
     scanner.useDelimiter(":"); 

     String name = scanner.next(); 
     String lang = scanner.next(); 
     String sex = scanner.next();    
    }catch(FileNotFoundException ex) { 
     System.out.println(
       "Unable to open file '" + 
       fileName + "'");     
    }catch(IOException ex) { 
     System.out.println(
      "Error reading file '" 
      + fileName + "'"); 
    } 
} 
0
while((line = bufferedReader.readLine()) != null) { 
    String text = line; 
    String[] parts = string.split(":"); 
    String part1 = parts[0]; 
    String part2 = parts[1]; 
    String part2 = parts[2]; 
} 

看起來更適合您的代碼。

+0

歡迎堆棧溢出!儘管您可能已經解決了此用戶的問題,但僅有代碼的答案對於未來出現此問題的用戶來說並不是很有幫助。請編輯您的答案,以解釋爲什麼您的代碼可以解決原始問題。 –

0

如果文件中的文本的格式被預定義(即總是3份單:分開),那麼下面的應該是足夠了:

String text = readLineFromFile(filepath); 
String[] parts = text.split(":"); 
String name = parts[0]; 
String lang = parts[1]; 
String gender = parts[2]; 
+0

如何使用「readLineFromFile」?它給了我錯誤.. – Karlken

+0

@yinon它看起來像你從約翰克利夫的答案複製代碼。 – GriffeyDog

+0

@GriffeyDog這是相反的。檢查john的帖子的[history](http://stackoverflow.com/posts/42097986/revisions)。 – Izruo