我对Java编程非常陌生,因此是此查询。 我有一个用String,LocalDate,Boolean,Double定义对象的类。 我主要从输入文件中读取内容。使用文件,线,路径。 我将其存储在列表中。
如何为对象定义中的每个字段分配每个值? 尝试了以下操作,但遇到错误,该错误未定义为String的类型。
package com.bapu;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;
public class App {
public static void main(String[] args) throws IOException{
String inputFileName = "e:/input/instruct.csv";
List<String> list = new ArrayList<>();
try {
list = Files.lines(Paths.get(inputFileName))
.map(s -> s.trim())
.skip(1)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
// list.forEach(System.out::println);
List<Instruction1> instruct1 = list.stream()
.map(p -> {
Instruction1 instruct2 = new ClientInstructions(
instruct1.setClientName(p.getClientName()),
instruct1.setFlag(p.getFlag()), // etc etc......
//return instruct1;
); })
.collect(Collectors.toList());
} // main()
} //class()
In another java file , I have the class object defined.
package com.bapu;
import java.time.LocalDate;
public class Instruction1 {
private String clientName;
private Boolean flag ;
// etc etc variables
public Instruction1(String clName1, Boolean flag1.... ) {
super();
this.clientName= clName1;
this.flag = flag1;
} // argument Constructor
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
/// all getters setters. followed hereafter
}
} // class Instruction1
此处不了解信息逻辑流程。 要求指导。 预先非常感谢。
答案 0 :(得分:0)
这对您有帮助吗?
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
class Instruction {
private String clientName;
private Boolean flag;
public Instruction(String clientName, Boolean flag) {
super();
this.clientName = clientName;
this.flag = flag;
}
@Override
public String toString() {
return String.format("ClientName : %s, Flag : %s", this.clientName,
this.flag);
}
}
public class App {
static BiFunction<String, Boolean, Instruction> createInstrucationFn = (
client, flag) -> new Instruction(client, flag);
public static void main(String[] args) throws IOException {
String inputFileName = "e:/input/instruct.csv";
List<String> dataLine = Files.readAllLines(Paths.get(inputFileName));
List<Instruction> instructionList = dataLine
.stream()
.map(line -> {
String[] pairs = line.split(",");
return createInstrucationFn.apply(pairs[0], Boolean.valueOf(pairs[1]));
}).collect(Collectors.toList());
instructionList.forEach(System.out::println);
}
}
在此示例中,假定文件为。
Client-A,true
Client-B,true
输出:
ClientName : Client-A, Flag : true
ClientName : Client-B, Flag : true