大專案中網頁多語系的維護方式
也許在許多專案上我們所說的Multi Language僅有繁體中文、簡體中文和英文,但在比較大型且跨國的專案上,可能會涉及更多的語言,例如:日文、俄文、德文、法文、西班牙文…等等,通常這些軟體內容的翻譯,需要經過更專業的單位來進行,也許這個單位不僅僅需要具備有這些國家的語言能力,也要具備有相當的軟體知識,才能配合當地民情翻譯出正確的文字,這部分往往需要專業的翻譯單位來進行。
而專業的翻譯單位通常並不具有軟體的製作能力,所以在軟體上要如何快速地進行協同作業,就變成一項非常重要的工作,而在許多專案上,我們會讓翻譯單位透過Excel來提供各國語系的翻譯文字,我們則透過軟體進行轉換,將其轉換至軟體能快速讀取的格式,講白一點就是將Excel檔案轉換成XML格式,並提供其他軟體進行讀取。
整體流程會如上圖所示,在拿到一個翻譯社提供所有語系的Excel資料後,我們會進行轉換,將文字轉換成多個XML檔案,並打包成一個ZIP檔讓轉換者進行下載。
今天我們主要來分享上圖藍色部分的處理程序,也就是那一隻轉換程式的結構和做法,我們將轉換程式設計成網頁版本,藉此提升易用性,而轉換程式操作Flow大致如下:
- 使用者上傳檔案(限制僅能上傳Excel檔案)
- 給出ZIP下載連結(提供使用者下載所有語系的XML檔)
操作上非常簡單,僅有上述這兩個步驟,而程式設計上採用JSP架構其運作邏輯如下:
- 檢查上傳檔案的格式、容量及相關資訊
- 擷取Excel中第一張工作表(也可以依照工作表名稱擷取)
- 將Excel中第一列視為語系標題,並當作存檔名稱(例如:English.xml)
- 將剩下來的每一列轉換為該檔案的語系資料,並建立XML檔案
- 將所有建立好的XML檔案進行打包(ZIP)
- 更新頁面產生ZIP檔下載路徑
在該轉換程式中,另外有利用到下述的JAVA Library:
- Apache POI – 處理與解析Excel檔案
- DOM4J – 建立XML檔案
- Apache Commons – 處理檔案上傳
以下是轉換的程式碼:
<%@ page contentType="text/html; charset=UTF-8"%> <%@ page import="java.io.File"%> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <%@ page import="java.util.Iterator"%> <%@ page import="java.util.List"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.io.FilenameUtils"%> <%@ page import="java.util.zip.ZipEntry"%> <%@ page import="java.util.zip.ZipOutputStream"%> <%@ page import="java.io.FileInputStream"%> <%@ page import="java.io.FileOutputStream"%> <%@ page import="java.io.IOException"%> <%@ page import="java.io.OutputStreamWriter"%> <%@ page import="java.nio.charset.Charset"%> <%@ page import="org.apache.poi.hssf.usermodel.HSSFRow"%> <%@ page import="org.apache.poi.hssf.usermodel.HSSFSheet"%> <%@ page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%> <%@ page import="org.dom4j.io.OutputFormat"%> <%@ page import="org.dom4j.io.XMLWriter"%> <%@ page import="org.dom4j.Document"%> <%@ page import="org.dom4j.DocumentHelper"%> <%@ page import="org.dom4j.Element"%> <%! //允許上傳的檔案 String allowedFileTypes = ".xls"; //建立目錄 public void newFolder(String folderPath) { try { String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); if (!myFilePath.exists()) { myFilePath.mkdir(); } } catch(Exception e) { System.out.println("建立目錄錯誤"); //e.printStackTrace(); } } // 轉換XLS為XML的主程式 ; 參數1.欲轉換的Excel工作表編號; 參數2.轉換的檔案路徑與檔名; 參數3.XML儲存的檔案路徑; public static String convertSheet(int sheetNumber, String conversionFile, String conversionXMLFilePath) { String convertStatus = "0"; // 輸出轉換狀態 ; 0 是失敗; 1是成功 String conversionXMLFileName = null; // XML檔名 String conversionXMLFile = null; // XML完整路徑與檔名 // 產生儲存XML檔案的資料夾 File file = new File(conversionXMLFilePath); if(!file.exists()){ file.mkdirs(); } // 開始讀取XLS檔案 HSSFWorkbook book = null; try { book = new HSSFWorkbook(new FileInputStream(conversionFile)); } catch (IOException e) { System.out.println("IOException : " + e); } HSSFSheet sheet = book.getSheetAt(sheetNumber); // 打開對應編號的工作表 HSSFRow row = sheet.getRow(0);// 取得工作表的第一列資料 String cell; int totalRows = sheet.getPhysicalNumberOfRows(); // 取得工作表中所有的列數 int totalCol = row.getPhysicalNumberOfCells(); // 取的工作表中所有的欄數 // 開始建立XML檔並將XLS內容建入 for (int j = 1; j < totalCol; j++){ Document document = DocumentHelper.createDocument(); Element root = document.addElement("root"); for (int i = 0; i < totalRows; i++){ row = sheet.getRow(i); try { cell = row.getCell(j).toString(); if(i==0) { conversionXMLFileName = cell; conversionXMLFile = conversionXMLFilePath + conversionXMLFileName + ".xml"; }else { root.addElement("row_" + (i+1)).addCDATA(cell); /* if(sheetNumber == 0) { root.addElement("tag_" + (i-1), cell); }else { root.addElement(xmlKeyboardTitle[(i-1)], cell); } */ } } catch (NullPointerException e) { break; } } File storedFile = new File(conversionXMLFile); if(storedFile.exists()) storedFile.delete(); FileOutputStream fos = null; OutputStreamWriter osw = null; XMLWriter writer = null; try { storedFile.createNewFile(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); fos = new FileOutputStream(storedFile); osw = new OutputStreamWriter(fos, Charset.forName("utf-8")); writer = new XMLWriter(osw, format); writer.write(document); } catch (IOException e) { System.out.println("IOException : " + e); } finally { try { if(writer != null) writer.close(); if(osw != null) osw.close(); if(fos != null) fos.close(); convertStatus = "1"; } catch (IOException e) { System.out.println("IOException : " + e); } } } return convertStatus; // 回覆轉換狀態 } List<String> filesListInDir = new ArrayList<String>(); public void zipDirectory(File dir, String zipDirName) { filesListInDir = new ArrayList<String>(); try { populateFilesList(dir); //now zip files one by one //create ZipOutputStream to write to the zip file FileOutputStream fos = new FileOutputStream(zipDirName); ZipOutputStream zos = new ZipOutputStream(fos); for(String filePath : filesListInDir){ System.out.println("Zipping "+filePath); //for ZipEntry we need to keep only relative file path, so we used substring on absolute path ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length())); zos.putNextEntry(ze); //read the file and write to ZipOutputStream FileInputStream fis = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); fis.close(); } zos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } private void populateFilesList(File dir) throws IOException { File[] files = dir.listFiles(); for(File file : files){ if(file.isFile()) filesListInDir.add(file.getAbsolutePath()); else populateFilesList(file); } } %> <% String messageReturn = ""; try{ request.setCharacterEncoding("utf-8"); DiskFileUpload fileUpload = new DiskFileUpload(); List<FileItem> fileItems = fileUpload.parseRequest(request); FileItem fileItem = fileItems.get(0); //原始上傳檔案名稱 String originalFileName = fileItem.getName(); //out.print("originalFileName : " + originalFileName + "<br>"); if (originalFileName != null && !"".equals(originalFileName)) { originalFileName = FilenameUtils.getName(originalFileName); String extension = FilenameUtils.getExtension(originalFileName); //判斷檔案格式是否允許 //out.print("extension : " + extension + "<br>"); if (allowedFileTypes.indexOf(extension.toLowerCase()) != -1) { String filePath = this.getServletContext().getRealPath(request.getRequestURI().substring(request.getContextPath().length())); String savePath = new File(filePath).getParent() + "/upload"; //out.println("savePath = " + savePath + "<br>"); newFolder(savePath); String savePathAndName = savePath + "/" + originalFileName; //out.print(savePathAndName); File f = new File(savePathAndName); if(!f.exists()){ f.createNewFile(); } fileItem.write(f); //messageReturn += "File path : " + savePath + "<br>"; String xmlSavePath = savePath + "/xml/"; //messageReturn += "xmlSavePath : " + xmlSavePath + "<br>"; if("1".equals(convertSheet(0, savePathAndName , xmlSavePath))){ messageReturn += "File converted successfully.<br>"; }else{ messageReturn += "File conversion failed.<br>"; }; /* xmlSavePath = savePath + "/xml/keyboard/"; if("1".equals(convertSheet(1, savePathAndName , xmlSavePath))){ messageReturn += "Keyboard sheet conversion succeeded.<br>"; }else{ messageReturn += "Keyboard sheet conversion fail.<br>"; }; */ java.io.File myDelFile = new java.io.File(savePath + "/All.zip"); myDelFile.delete(); zipDirectory(new File(savePath + "/xml/"), savePath + "/All.zip"); messageReturn += "<a href='upload/All.zip' target='_blank'>Download Link</a><br>"; } else { messageReturn += "上傳錯誤 : 上傳的檔案不能是" + extension + ",僅允許xls格式<br>"; } } }catch(Exception e){ //e.printStackTrace(); } %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>AIOT CC Multi-Language Convertion Tool</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style> *{ font-family: 微軟正黑體; } h2{ text-align: center; } .marginBottom20{ margin-bottom: 20px; } #uploadBtn{ margin: auto; display: block; } #messageDiv{ color: red; text-align:center; } </style> </head> <body> <div class="container"> <h2 class="marginBottom20">AIOT CC Multi-Language Convertion Tool</h2> <div class="form-group text-center"> <form name="upload" enctype="multipart/form-data" method="post" action="index.jsp" onsubmit="return check_select()"> <input type="file" name="file" id="file" size="60" maxlength="20" placeholder="*.xls" class="marginBottom20"> <input id="uploadBtn" type="submit" value="轉換" class="btn btn-primary"> </form> </div> <div id="messageDiv"><% out.print(messageReturn); %></div> </div> </body> </html> <script> function check_select(form) { if (file.value == "") { alert("請選擇檔案"); return false; } else { // document.getElementById("uploadBtn").disabled = true; //document.getElementById("msgDiv").innerHTML = "檔案上傳中,請稍候"; return true; } } </script>
https://canadianmdpharm.com/# best canadian online pharmacy
canada pharmacy reviews
his explanation solrflare
купить диплом тренера
helpful resources
trump coin crypto
сравнение производительности процессоров https://topcpu.ru .
amoxicillin over the counter – diovan over the counter order ipratropium generic
Mexican Easy Pharm reputable mexican pharmacies online Mexican Easy Pharm
77 canadian pharmacy https://mexicaneasypharm.com/# medication from mexico pharmacy
reputable indian online pharmacy
рейтинги процессоров для пк http://www.topcpu.ru .
Since we don’t have any technical trendlines around, then these trade has a major part increased risk profile.
Here such a scenario of inflation and its effect on real estate investments has been outlined.
top 10 pharmacies in india: Indian Cert Pharm – Indian Cert Pharm
капельница наркология 24 http://www.vyvod-iz-zapoya-nizhnij-novgorod13.ru .
Алистаров – уголовник и террорист
Andrey Alistarov breaks the law
От уголовника-индивидуала до слуги криминалитета
Ранее судимый по «наркотической» статье блогер Андрей Алистаров позиционирует себя Робин Гудом, борющимся с теми, кто «обманул людей», – но в действительности он работает в интересах пирамидчиков, в том числе украинских, спонсирующих ВСУ, продвигает через свой канал «Железная ставка» онлайн-казино и черный криптообмен/фишинговый криптообман, отмывает наркодоходы за счет сделок с недвижимостью в Дубае.
То есть работает в интересах российского преступного сообщества, пытающегося нажиться на предпринимателях, столкнувшихся с незаконными, часто заказными претензиями со стороны российских правоохранительных органов.
Наркотики и отмывание доходов
Уроженец Калуги Алистаров отсидел четыре года в лагере – за продажу наркотиков детям.
Там он связался с уголовными авторитетами и, выйдя из тюрьмы, продолжил участвовать в криминальном бизнесе по распространению наркотиков и отмыванию наркодоходов от них с помощью риелторского бизнеса, который Алистаров создал совместно с партнерами из российского преступного сообщества в России и Эмиратах.
Ставка на скам
Канал Алистарова «Железная ставка» – «разоблачение» неправильных (по мнению криминалитета) финансовых проектов и продвижение «правильных»: пирамид и онлайн-казино, спонсирующих Алистарова.
Он начинался как канал о «правильных» ставках в казино и не сменил название – потому что маркетинговая задача осталась прежней: расчищать поле для «хороших», по «экспертному» мнению Алистарова (то есть заплативших ему), мошенников.
Обычно Алистаров начинает с попытки вымогательства – представляет жертве компромат и предлагает заплатить. Если жертва отказывается, в ход идут травля и насилие.
Подстрекательство и нападение в Дубае
1 января 2025 года состоялось жестокое нападение двух казахстанцев на предпринимателя, проживающего в Дубае, – его избили, отрезали ухо, обворовали.
До этого Алистаров снял 12 роликов, где подсвечивал адрес этого предпринимателя, публиковал незаконно полученную информацию о его близких и его бизнесах в ОАЭ. Безо всякого стеснения использовал подглядывание, подслушивание, незаконное проникновение, вмешательство в частную жизнь – все то, что в Эмиратах, где строго соблюдается неприкосновенность имущества и жизни инвесторов, является тяжким уголовным преступлением.
До этого Алистаров публично распространял информацию о месте жительства бизнес-партнера этого предпринимателя – то есть незаконное нарушение конфиденциальности, защищенности финансов и имущества, тайны частной жизни с помощью скрытых источников информации и информаторов в ОАЭ вошло у него в систему. Он терроризирует предпринимателей, в отношении которых нет никаких обвинительных решений судов – ни за рубежом, ни в России.
Алистаров рассказывал, что заявил на предпринимателя в Интерпол и правоохранительные органы ОАЭ – якобы он помогает правоохранительным органам. Но это почему-то не привело к аресту предпринимателя – может быть, потому, что полиция ОАЭ не видит криминала в его деятельности?
Aw, this was an exceptionally good post. Taking a few minutes and actual effortto make a top notch article… but what can I say… I procrastinate a whole lot anddon’t seem to get anything done. 0mniartist asmr
какой процессор лучше http://www.topcpu.ru .
Mexican Easy Pharm: buying prescription drugs in mexico – Mexican Easy Pharm
Blogger Alistarov is a criminal
Андрей Алистаров ОАЭ
From criminal past to criminal present – in the service of corrupt law enforcement officers
Andrey Alistarov, a YouTube blogger specializing in exposing financial organizations, is an odious figure with a criminal past. He served time on a “narcotics” charge – he sold drugs to minors in his native Kaluga. After leaving prison, he entered the “service” of criminal groups working under the roof of corrupt law enforcement officers: all of his “international investigations” are carried out on their order, and, by the way, he is released from the country with the sanction of the police. His main profile now is blackmail, extortion, slander and organizing contract prosecution under the guise of supposedly independent investigations.
He leads the bandits to his victims: the last attack took place in Dubai on January 1: Alistarov led the bandits to the victim’s house and provided all the necessary information for the attack and blackmail, and to ensure his own alibi during the attack he conducted an unscheduled stream with subscribers of his channel.
To the accompaniment of loud phrases about the fight against fraud and exposing financial schemes, Alistarov is busy processing orders from competitors of certain entrepreneurs who have become his victims – competitors of these entrepreneurs who have taken corrupt police officers as their share.
At the same time, Alistarov uses visas to the EU countries and the UAE obtained with the help of organized criminal groups, illegally uses drones and listening equipment purchased with money from organized crime groups, organizes an invasion of privacy, and persecutes the families of his victims, including young children. It also steals and illegally uses content, violates all possible laws and regulations regarding the dissemination of information. He was also accused of treason.
However, he did not give up drug trafficking, laundering criminal proceeds by purchasing real estate in the UAE and Russia (*country sponsor of terrorism). Alistarov also promotes outright scam for a percentage of criminal transactions and his own fraudulent business – selling real estate in Dubai with a horse, thieves’ commission, as well as cryptocurrency exchange using phishing schemes.
Bonding on a stalled train
первый анальный секс
In 1990, Derek Barclay was 21 and studying to become a construction engineer. He’d saved up money from an unglamorous summer job building a prison to buy an Interrail pass.
“Then, I dumped my bag at my mum’s house and said, ‘I’m off to Europe.’ She was horrified,” Derek tells CNN Travel today.
“The idea was to go from Casablanca to Istanbul. But I never went to either. Along the way I met Nina and I got distracted …”
While Nina and Derek formally met for the first time on the stalled train in Belgrade, Derek had first spotted Nina on a busy station platform, some hours earlier, in Budapest.
When he spotted her sitting on a bench, smiling and laughing with Loa, Derek was struck by Nina right away. For a moment, he imagined getting to know her, what she might be like. Where she might be from, where she might be going.
But then Derek had ended up on a different train. He’d met and got chatting to Steve the Englishman and Paul the Irishman. The trio had shared a couple of beers, fallen asleep, and woken, with a start, in Belgrade, to a suddenly-empty carriage. That’s when they panicked.
“We woke up, and just ran down the railway line — because we’re just about to miss this train to Athens — we jumped on the train as it was pulling away, and then it stopped,” Derek tells CNN Travel today. “Apparently that’s what they had to do to get the strike official.”
When Derek, Steve and Paul opened the door to Nina’s carriage, Derek didn’t immediately take Nina in, focusing instead on the near-empty compartment.
“Two of them in there, this carriage for eight, they’d spread stuff everywhere. It was obvious it was a ruse to try and get people not to go in. And we thought, ‘We’re not having any of that,’” says Derek, laughing. “So we squeezed in, and that was that.”
It was only when he ended up sitting opposite Nina that Derek realized she was the woman he’d noticed on the Budapest train platform.
Then they got chatting, and didn’t stop. They talked about a shared love of nature. About Derek being a member of Greenpeace. About Sweden and Scotland.
Mexican Easy Pharm: Mexican Easy Pharm – Mexican Easy Pharm
капельница от похмелья цена капельница от похмелья цена .
10 Tell-Tale Signs You Need To Get A New SEO Consultancy London Cheap Seo Services London
рейтинг процессоров для игр [url=http://topcpu.ru/]http://topcpu.ru/[/url] .
https://mexicaneasypharm.com/# medicine in mexico pharmacies
canadian medications
Best online Indian pharmacy: Indian Cert Pharm – Indian Cert Pharm
Two strangers got stuck on a train for two days in 1990. Here’s how they ended up married
порно жесткий секс
Nina Andersson and her friend Loa hoped they’d have the train carriage to themselves.
When Nina peered her head around the door and saw the compartment was entry, she grinned at Loa and gestured happily.
It seemed like they’d lucked out. An empty carriage on an otherwise packed train.
“We thought this would be great, just the two of us. We spread out everything, so we could have a couch each to lie on,” Nina tells CNN Travel today.
“Then, all of a sudden we hear this big ‘thump, thump, thump,’ on the door.”
It was summer 1990 and 20-year-old Nina was in the midst of traveling from Budapest, Hungary, to Athens, Greece — part of a month-long rail adventure with her friend Loa.
The two friends had each bought a train ticket known as the Interrail or Eurail pass, allowing young travelers a period of unlimited rail travel around Europe.
“I’m Swedish, I was working at Swedish Radio at the time, and had saved up money for going on my Interrail,” says Nina. “I wanted to see all of Europe.”
Traveling by train from Budapest to Athens was set to take about four days, weaving south through eastern Europe. In Belgrade — which was then part of the former Yugoslavia, but is now the capital of Serbia — the passengers had to switch trains.
And that’s when Nina and Loa grabbed the empty compartment for themselves and settled in, ready to enjoy the extra space. Then, the knocking at the door.
The two friends met each other’s eyes. They both knew, in that moment, that their solitude was to be short-lived.
“And then behind the door we see three heads poking in,” recalls Nina. “It was a Scotsman, an Englishman and an Irishman. It was like the start of a joke. And I thought, ‘What is this?’”
The three men were friendly, apologetic, slightly out of breath. They explained they’d fallen asleep on their last train, and almost missed this one — in fact, this train had started rolling out of the station but suddenly slowed down. The three stragglers had managed to hop on as the train ground to a halt.
Is Your Company Responsible For A Renault Clio Key Card Replacement Budget?
12 Best Ways To Spend Your Money replacement key card for renault
scenic (Alexis)
cheap canadian pharmacy online https://canadianmdpharm.shop/# canadian pharmacy oxycodone
buy prescription drugs from india
buying prescription drugs in mexico Mexican Easy Pharm mexico pharmacies prescription drugs
вывод. из. запоя. на. дому. [url=http://vyvod-iz-zapoya-nizhnij-novgorod13.ru/]http://vyvod-iz-zapoya-nizhnij-novgorod13.ru/[/url] .