2017-02-07 37 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