我已經嘗試了StackOverflow上其他執行緒建議的多種解決方案,但我沒有找到解決方案。我試圖使用 Java 讀取一個 .txt 檔案并將內容從大到小排序。這就是我的.txt檔案所包含的內容:
16° C
15° C
18° C
13° C
17° C
19° C
21° C
20° C
16° C
以下是我所嘗試的:
import java.io.*;
import java.util.*;
public class temperatur {
public static void main title function_">main(String[] args) throwsIOException {
BufferedReader reader = null。
PrintWriter outputStream = null;
ArrayList<String> rows = new ArrayList<String>()。
try {
reader = new BufferedReader(newFileReader)。
outputStream = new PrintWriter(new FileWriter("tempout.txt") )。)
字串檔案。
while ((file = reader .readLine()) != null) {
rows.add(file)。
}
Collections.sort(rows)。
String[] strArr= rows.toArray(new String[0] )。)
for (String cur : strArr)
outputStream.println(cur)。
} finally {
if (reader != null) {
inputStream.close()。
}
if (outputStream != null) {
outputStream.close()。
}
}
}
}
uj5u.com熱心網友回復:
這將讀取temp.text并分割每一行以獲得數字部分(考慮到它總是在°符號之前)以添加到一個tempList中,然后進行排序。然后將排序后的串列與輸入檔案中給定的其余字串連接起來,寫入輸出檔案中。
import java.io.*;
import java.util.*;
public class temperatur{
public static void main title function_">main(String[] args) throwsIOException {
File file = new File("temp. txt")。)
List<Double> tempList = new ArrayList() 。
BufferedReader br = new BufferedReader(new FileReader(file))。
字串st。
while ((st = br.readLine()) != null) {
String[] temp = st.split("°"/span>)。
tempList.add(Double.parseDouble(temp[0] )。
}
Collections.sort(tempList)。
Collections.reverse(tempList)。
//Write into a new file
FileWriter file2 = new FileWriter("tempout. txt")。)
String sb = "" ;
for (double a : tempList) {
sb = a "°"/span> " C
"/span>。
}
file2.write(sb);
file2.close()。
}
}
tempout.txt
21.0°C
20.0° C
19.0° C
18.0° C
17.0° C
16.0° C
16.0° C
15.0° C
13.0° C
uj5u.com熱心網友回復:
下面是一個使用較新技術的例子,如java.nio而不是java.io,用于檔案系統操作以及流式資料:
public static void main(String[] args) throws IOException {
//將檔案的路徑定義為String(使用你的路徑!)
String temperaturesFile = "/path/to/temperatures.txt"/span>。
//從它創建一個 java.nio.Path。
Path temperaturesPath = Paths.get(temperaturesFile) 。
//檢查它是否存在。
if (Files.exists(taturesPath, LinkOption.NOFOLLOW_LINKS)) {
//然后檢查它是否真的是一個普通檔案。
if (Files.isRegularFile(taturesPath, LinkOption.NOFOLLOW_LINKS) {
//并檢查該檔案是否可讀。
if (Files.isReadable(taturesPath)) {
//然后讀取它的所有行數//stream them
.stream()
//反向排序。
.sorted(Comparator.reverseOrder())
//將結果收集到一個List中。
.collect(Collectors.toList())。
//最后列印結果串列的元素。
sortedLines.forEach(System.out::println)。
}
}
}
}
請注意
這段代碼對于你發布的檔案例子來說是很好的,因為該檔案既不包含負的溫度值(如果溫度是用攝氏度測量的,很可能會有這樣的溫度值),也不包含超過99的溫度值(在攝氏度中不太可能,我承認)。
這個例子用詞典的方式比較Strings,這對作為例子的數字來說是可以的,但如果上述的變化之一出現,就會崩潰/失敗。為了解決這些問題,你必須提供從普通String到TemperatureCelsius類的轉換。也許提取數值(包括符號)就足以獲得一個正確的排序順序。
然而,用有效路徑中的有效檔案執行這段代碼的結果是:
21° C
20° C
19° C
18° C
17° C
16° C
16° C
15° C
13° C
uj5u.com熱心網友回復:
你應該決議你的資料,例如:
你應該決議你的資料。
static Pattern temperatureRegex = Pattern. compile("^([0-9] )°C$")。
private static int parseTemperature(String s) {
return of(temperatureRegex.matcher(s)) //得到一個匹配器。
.filter(Matcher::find) // 必須找到
.map(m -> parseInt(m.group(1) ) //轉為整數。
.orElseThrow(); //或例外。
}
然后,簡單地讀和寫行映射與排序
。write(Paths.get("/home/josejuan/tmp/Tout.txt") 。
readAllLines(Paths.get("/home/josejuan/tmp/T.txt") .stream()
.sorted(Comparator.comparingInt(SortFile::parseTemperature)).collect(toList())。
(Aside full code)
package com.computermind.sandbox.fileprocessing。
import java.io.IOException;
import java.nio.file.Paths。
import java.util.com比較器。
import java.util.regex.Matcher;
import java.util.regex.Pattern。
import static java.lang.Integer.parseInt;
import static java.nio.file.Files.readAllLines;
import static java.nio.file.Files.write。
import static java.util.Optional.of。
import static java.util.stream.Collectors.toList;
public class SortFile {
static Pattern temperatureRegex = Pattern.compile("^([0-9] )°C$") 。
private static int parseTemperature(String s){
return of(temperatureRegex.matcher(s)) //得到一個匹配器。
.filter(Matcher::find) // 必須找到
.map(m -> parseInt(m.group(1) ) //轉為整數。
.orElseThrow(); //或例外。
}
public static void main(String. .args) throws IOException {
write(Paths.get("/home/josejuan/tmp/Tout.txt") 。
readAllLines(Paths.get("/home/josejuan/tmp/T.txt") .stream()
.sorted(Comparator.comparingInt(SortFile::parseTemperature)).collect(toList())。
}
}
uj5u.com熱心網友回復:
擴展我的評論,這里是如何對你已經擁有的rows中的行進行排序的例子。這是假設你想保留原始的行,而不是重建它們。
決議和排序
通常使用一個類來保存該行的內容和數值,例如:
//simplified, add setters, getters etc.
class Line {
字串內容。
double temp;
}
并且在閱讀行時建立:
List<Line> rows = ...
字串lineContent。
while ((lineContent= reader .readLine()) != null) {
double temp = Double.parseDouble(lineContent.split("°")[0] )。)
rows.add(new Line(lineContent, temp))。
}
然后排序:
Collections.sort(rows, Comparator.comparing(Line::getTemp).reversed());
直接對字串進行排序
字串是通過比較字符來排序的,因此"10"將被認為比"2"小。因此,我們需要使用一個 "技巧":
- 首先按長度排序,所以2比10小 。
- 然后按詞法排序 。
Collections.sort(rows, Comparator.comparing(String::length)
.thenComparing(Function.identity())
.反轉())。
注意,如果數字可以變成負數或有不同的格式(即不同長度的分數、不同數量的空格、行中的額外資料等),這就會被打破。在這些情況下,編譯器將需要更加復雜,而且復雜度越高,使用 "決議和排序 "方法就越容易。
為了供您參考,這里有一個比較器,它應該能夠對相同格式(相同分數數字等)的字串進行排序,支持符號( 和-):
Collections.sort(rows, (String left, String right) -> {
char c1Left = left.charAt(0);
char c1Right = right.charAt(0)。
int direction = -1; /1為升序。
//負數小于0或正數。
int result = Integer.compare(c1Left == '-'/span> ? -1 : 0, c1Right == '-' ? -1 : 0)。)
if( result != 0) {
return 結果 * 方向。
}
//此時,兩個數字要么都是正數要么都是負數。
//對于負數,我們需要保留方向,因為我們將只比較 "絕對值"。
if( c1Right == '-'/span> ) {
方向 *= -1。
}
String subLeft = Character.isDigit(c1Left) ? left : left.substring(1) 。
String subRight = Character.isDigit(c1Right) ? right : right.substring(1) 。
//較短的數字比較長的數字要小(照顧到2與10或3.1與21.0這樣的情況)。
結果 = Integer.compare(subLeft.length(), subRight.length())。
if( result != 0) {
return 結果 * 方向。
}
//sign和length是相等的,剩下的就是簡單的字符比較。
結果 = subLeft.compareTo(subRight)。
return 結果 * 方向。
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333336.html
標籤:
