java - 从 URL 中逐行读取文本文件,打印到 txt 文件并在打印时进行编辑
问题描述
该程序读取此处可用的衬衫尺寸文件的每一行:https : //bbmedia.dmacc.edu/CIS/CIS171/shirtsizes.txt 并将所有订购小衬衫的人写入一个名为“smallshirts.txt”的文件中,中号订单进入“mediumshirts.txt”文件,大号订单进入“largeshirts.txt”文件,最后超大号衬衫进入“extralargeshirts.txt”文件。
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Scanner;
public class SortShirtSizes {
/**
* This main method will get a file from the URL and separate it into different txt files
*/
public static void main(String[] args) throws IOException {
try {
/*getting the txt from the URL*/
String address = "https://bbmedia.dmacc.edu/CIS/CIS171/shirtsizes.txt";
URL pageLocation = new URL(address);
Scanner in = new Scanner(pageLocation.openStream());
/*names of txt files*/
PrintWriter outToSmall = new PrintWriter("smallshirts.txt");
PrintWriter outToMed = new PrintWriter("mediumshirts.txt");
PrintWriter outToLarge = new PrintWriter("largeshirts.txt");
PrintWriter outToXl = new PrintWriter("extralargeshirts.txt");
outToSmall.println("");
String small = "";
while (in.hasNextLine()) {
small = in.nextLine();
/*print to txt files*/
if (small.contains("S,")) {
outToSmall.println(small);
}else if (small.contains("M,")) {
outToMed.println(small);
}else if (small.contains("XL,")) {
outToXl.println(small);
}else if (small.contains("L,")) {
outToLarge.println(small);
}
}
in.close();
outToSmall.close();
outToMed.close();
outToLarge.close();
outToXl.close();
}catch (IOException e) {
System.out.println("https://bbmedia.dmacc.edu/CIS/CIS171/shirtorders2022.txt is not available.");
}
}
}
输出示例:
S,Darsie,Rigmand
M,Feodor,Lornsen
L,Klement,Antunes
XL,Carleton,Van Leeuwen
我想删除名字和姓氏之间的 S、M、L、XL 和 ,。
解决方案
有很多方法可以做到这一点。但是当有一些可用的库时,我喜欢使用库。您可以做的是使用Apache Commons CSV 库来读取逗号分隔文件。获取信息并根据需要做任何事情。要添加库,这里是Maven Repo 链接。
例子:
URL url = new URL("https://bbmedia.dmacc.edu/CIS/CIS171/shirtsizes.txt");
Reader fileReader = new InputStreamReader(url.openStream()); // Reading the Content of the online FIle
CSVFormat format = CSVFormat.Builder
.create()
.setDelimiter(",")
.setHeader("size", "first_name", "last_name")
.build(); // Setting the headers and delimiters for this specific format
CSVParser csvParser = new CSVParser(fileReader, format);
for(CSVRecord record : csvParser)
{
String size = record.get("size");
String firstName = record.get("first_name");
String lastName = record.get("last_name");
// Do whatever you want with the information above.
}
推荐阅读
- spring-boot - 如何创建未发现异常的单元测试?
- python - How to display a data frame read into python through Pandas in a window using Tkinter on Python 3.8?
- python-3.x - 在python中,根据图像文件的名称来考虑图像文件进行计算
- python - 所有转换的累积和
- java - 使用 amazon SES SMTP 接口发送电子邮件后如何获得响应?
- python - 如何为 numpy 数组“x”实现函数 f(x) = { x^2, x>0 和 -x^2 , x<0 }?
- html - 订单列表的浮动图像和文本换行
- postgresql - 将 ISO8601 日期文本转换为时间戳
- json - 如何从 Swift 中的 JSON 文件中读取混合类型的数组?
- import - Power BI - 批量导入/导出措施