我在一个项目中工作,我想要一些帮助。
所以这是我的测试代码:
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)我想在一个名为“name”的字符串中写入':'(Karlken)之前的第一个单词,第二个单词写在另一个字符串(Java)中的':'之后,最后再写在另一个字符串中字符串我想写“男”我怎么样?
答案 0 :(得分: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];
}
似乎更适合您的代码。
答案 1 :(得分:0)
如果文件中的文本格式是预定义的(即总是由单个:
分隔的3个部分),那么以下内容应该足够了:
String text = readLineFromFile(filepath);
String[] parts = text.split(":");
String name = parts[0];
String lang = parts[1];
String gender = parts[2];
答案 2 :(得分: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 + "'");
}
}