2017-04-12 23 views
-1

我有包含鸣叫及其例如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 

我想创建的每一行并将其命名为ID为一个新文件的文件而这个文件里面我想提出的鸣叫文本 拿第一线为例"1 what a nice day" 的文件名应该是(1.txt)和文件中"what a nice day"

我真的没有任何想法如何做到这一点你能请帮帮我?

+0

参见[读,写和创建文件](https://docs.oracle.com/javase/tutorial/essential/ io/file.html)在Oracle的Java教程中。 – Jesper

回答

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,与姓名的数量,作为内容的句子 如果有任何问题,告诉我在评论

编辑:我评论更好的代码,以帮助您

+0

大声笑实际上这些都是推文的ID它必须保持,所以我不能改变它 UTF-16BE没有显示任何错误,但没有创建的文件 – Qubayl

+0

那么ID是如何?因为在你的屏幕截图上5是相同的^^ – azro

+0

这些是其中的一些 https://ibb.co/bHWdBQ – Qubayl

相关问题