代码改变世界

[Java] Frequently used method or solutions for issues

2018-11-16 12:07  Johnson_强生仔仔  阅读(174)  评论(0编辑  收藏  举报

模板:

 

  • Split string into parts based on new line in java

    Solution:   Reference is here

        1)

 

  • get out of the first part of a string until meet "<"

    Solution:   Reference is public String[] split(String regex)

        1)  s = "boo:and:foo";     String[] result = s.split(":") ; => {"boo", "and", "foo"}

        2)  s = "boo:and:foo";     String[] result = s.split(":", 2) ; => {"boo", "and:foo"}

        3)  s = "boo.and.foo";     String[] result = s.split("\\.", 2) ; => {"boo", "and.foo"}

 

 

  • Split string into parts based on new line in java

    Solution:   Reference is here

        1) 

String lines[] = string.split("\\r?\\n");

 

  • Convert Long in int in java

    Solution:    

        1) 

int result = (int) longVar;

 

  • Copy file to another folder in java

    Solution:    Reference is herecopy(Path source, Path target)

        1) 

Path source = Paths.get("/Users/apple/Desktop/test.rtf");
Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");

Files.copy(source, destination);

 

  • File into a String in java

    Solution:    Reference is hereFiles.readAllBytes(Path source)

        1) 

String filePath = "c:/temp/data.txt";

String content = new String ( Files.readAllBytes( Paths.get(filePath) ) );

 

  • Path String to File in java

    Solution:   

        1)

String filePath = "c:/temp/data.txt";

File file = new File (filePath );

 

  • Join path in java

    Solution:   Reference is here

        1) Use Paths.get(String parentPath, args)

import java.nio.file.Path;
import java.nio.file.Paths;
Path currentPath = Paths.get(System.getProperty("user.dir")); Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");

output is "

/Users/user/coding/data/foo.txt

"

        2) Use File(String parentPath, fileName)

import java.io.File
File file = new File(parentPath, fileName);
System.out.println(file.getAbsolutePath());

 

  • Get epoch time in java (present a unique Id by numbers if the time is not in the same ms)

    Solution:   Reference is here

        1)

long epoch = System.currentTimeMillis();
String Id = Long.toString(epoch);

 

  • Create a path from String in java

    Solution:   Reference is here

        1)

import java.nio.file.Paths;
Path path = Paths.get(textPath);