[英]Read a text file from a URL line by line, print to a txt file and edit while being printed
該程序讀取此處提供的襯衫尺寸文件的每一行: 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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.