我有一个包含推文及其ID的文件,例如
user.upate_attributes(:token => token)
# Change to
user.update_attributes(:token => token)
我想为每一行创建一个新文件,并用ID命名,在这个文件中我想要发推文
以第一行为例1 what a nice day //1 is the ID and "what a nice day" is the tweet text
2 how are you doing //2 is the ID and "how are you doing" is the tweet text
.
.
. etc
文件名应为("1 what a nice day"
)且在文件1.txt
我真的不知道该怎么做才能帮助我吗?
答案 0 :(得分:0)
希望能帮助你:
public static void readSplitWrite(String pathToFile){
//To recognize how are your sentences : between 1 and 25 digit, then some spaces, and then what you want
Pattern patt = Pattern.compile("([0-9]{1,25})\\s*(.*)");
try {
//Read over all the lines of your file
for(String line : Files.readAllLines(Paths.get(pathToFile),Charset.forName("UTF-8"))){
//Catch the different parts of the string (group(0) is the hole sentence, group(1) is inside first (), group(2) is inside second ()
Matcher m = patt.matcher(line);
if(m.find()){
//Open a file, in UTF-8 encoding (to be able to read Arabic character, as name the ID
Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(m.group(1)+".txt"), "UTF-8"));
try {
//write the content into
out.write(m.group(2));
}catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//Just the name if the file is in the folder, if not write absolute path
String pathToFile = "Text.txt";
readSplitWrite(pathToFile);
}
此代码将读取您的文件,然后为每一行创建new File
,其中包含数字的名称,以及句子的内容
如果有任何问题,请在评论中告诉我
编辑:我更好地评论了帮助您的代码