gpt4 book ai didi

java - 将给定的字符串行打印到列中

转载 作者:行者123 更新时间:2023-12-01 12:52:39 25 4
gpt4 key购买 nike

我有 *.txt 文件,第一行为姓名、地址、邮件 ID,第二行为值。我必须将其打印成两列,第一列包含标题,第二列包含使用 Java 的值。我该怎么做呢?

public class ReadFile1 {

public static void main(String[] args) {
BufferedReader br=null;
String sCurrentLine = null;
String delimiter = ",";
String[] filetags;
try {
br = new BufferedReader(new FileReader("path\\Read.txt"));
sCurrentLine = br.readLine();
StringBuffer result = new StringBuffer();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
filetags = line.split(delimiter);
for(int i = 0;i < line.length(); i++)
{
System.out.println("****" +sCurrentLine);
String[] s = line.split(",");
for(int j = i-1; j<line.length();j++)
{
System.out.println("##############"+Arrays.toString(s));
}
}
}
}

这是我尝试过的。例如:我有一个文件说,

line1) name,email,mobile and second 
line2) john,j@abc.com,9876
line3) max,max@xyz.com,1234

现在,我需要打印:

name john
email john@abc.com
moblie 9876
name max
email max@xyz.com
mobile 1234

最佳答案

以下是您可能获得所需内容的一种方法,它与您尝试的方法类似,但稍微更精致。

文件:

 name,email,mobile and second
john,j@abc.com,9876
max,max@xyz.com,1234

代码:

    //File is on my Desktop
Path myFile = Paths.get(System.getProperty("user.home")).resolve("Desktop").resolve("tester.txt");
//Try-With-Resources so we autoclose the reader after try block
try(BufferedReader reader = new BufferedReader(new FileReader(myFile.toFile()))){
String[] headings = reader.readLine().split(",");//Reads First line and gets headings
String line;
while((line = reader.readLine()) != null){//While there are more lines
String[] values = line.split(","); //Get the values
for(int i = 0; i < values.length; i++){//For each value
System.out.println(headings[i] + ": " + values[i]);//Print with a heading
}
}
} catch (IOException io) {
io.printStackTrace();
}

祝你好运!

关于java - 将给定的字符串行打印到列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24107635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com