Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Java.io' - 34 code snippet(s) found

 Sample 1. Method to get all files from a directory recursively

List<File> fileList = new ArrayList();

List<File> read(String dir) throws IOException{
File directory = new File(dir);
File[] fList = directory.listFiles();
for(File file:fList){
if(file.isDirectory()){
read(file.getPath());
} else {
fileList.add(file);
}
}
return fileList;
}

   Like      Feedback     file handling   file   isDirectory()  .getPath()   recursion   java.io.File


 Sample 2. Get the content of a file in a string

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileToString {

public static void main(String[] args) throws IOException {

String line = null;

String wholePage = "";

FileReader fileReader =
new FileReader("/home/vivekvermani/test.txt");

BufferedReader bufferedReader =
new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {
wholePage = wholePage + line + "
";
}

bufferedReader.close();

System.out.println(wholePage);
}
}

   Like      Feedback     reading file to string  import


 Sample 3. Blogger API for creating Posts ( Change xxxxxx to your blog specific info )

package Reader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;

public class BlogPostCreater {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String title, String content,String label,String authorization_key) throws IOException {

content = content.replace(""",""");


String url = "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts?clientId=xxxxxxxx&clientSecret=xxxxxxxx";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("Authorization", authorization_key);
post.setHeader("Content-type","application/json");

post.setEntity(new StringEntity(buildJson(title,content,label)));

HttpResponse response = client.execute(post);

System.out.println(response);

return "true";
}



String buildJson(String title, String content,String label) {

System.out.println(label);
return "{"status": "LIVE", "content": ""+content+"", "kind": "blogger#post"" +
", "title": ""+title+"", "url": "xxxxxx", " +
""readerComments": "DONT_ALLOW_HIDE_EXISTING", "author": {" +
""url": "https://www.blogger.com/profile/04326686331881561093", " +
""image": {" +
""url": "//lh4.googleusercontent.com/-64Ucx9lX9Q4/AAAAAAAAAAI/AAAAAAAAAx0/-rUjBgS3djE/s35-c/photo.jpg"" +
"}, " +
""displayName": "Vivek Vermani", " +
""id": "g108356395081185480077"" +
"}, "updated": "2015-09-28T09:46:12+05:30", "replies": {"totalItems": "0", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts/2495464003469367152/comments"" +
"}, "blog": {"id": "4275342475651800664"}, " +
""etag": "'GtyIIQmNmmUjEA0nwhSqMElCJ1g/dGltZXN0YW1wOiAxNDQzNDEzNzcyMDc1Cm9mZnNldDogMTk4MDAwMDAK'", " +
""published": "2015-09-28T09:46:00+05:30", " +
""id": "2495464003469367152", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxx/posts/2495464003469367152"}";
}

public String post(String url, Map<String,String> formParameters) throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);

List <NameValuePair> nvps = new ArrayList <NameValuePair>();

for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}

request.setEntity(new UrlEncodedFormEntity(nvps));

return execute(request);
}

// makes request and checks response code for 200
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);

if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}

return body;
}


}

   Like      Feedback     blogger api   blogger api for post creation  java.lang.RuntimeException


 Sample 4. getting file path, absolute path and canonical path

public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}

   Like      Feedback     file  absolute path  canonical path  canonical  file handling  java.io.IOException


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Apache Kafka Consumer

https://apache.googlesource.com/kafka/+/trunk/examples/src/main/java/kafka/examples/Consumer.java?autodive=0%2F

   Like      Feedback     


 Sample 6. Apache Hadoop Map Reduce Example

https://apache.googlesource.com/hadoop-common/+/trunk/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/Grep.java

   Like      Feedback     


 Sample 7. Apache Hadoop Multi File Word Count

https://apache.googlesource.com/hadoop-common/+/trunk/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/MultiFileWordCount.java

   Like      Feedback     


 Sample 8. Usage of java.io.FileInputStream

FileInputStream fis = new FileInputStream("mypodcast.mp3");
InputStreamRequestEntity re = new InputStreamRequestEntity(fis, "audio/mp3");

   Like      Feedback     ileInputStrea


 Sample 9. Usage of java.io.ByteArrayOutputStream

ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);

   Like      Feedback     


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Internal Implementation of BufferedReader#lines

public Stream<String> lines() {
Iterator<String> iter = new Iterator<String>() {
String nextLine = null;

@Override
public boolean hasNext() {
if (nextLine != null) {
return true;
} else {
try {
nextLine = readLine();
return (nextLine != null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

@Override
public String next() {
if (nextLine != null || hasNext()) {
String line = nextLine;
nextLine = null;
return line;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}

   Like      Feedback     Internal Implementation of BufferedReader#lines


 Sample 11. Usage of java.io.ByteArrayInputStream

ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();

   Like      Feedback     ByteArrayInputStream  java.io  input stream  ObjectInputStream


 Sample 12. Usage of ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(validator);
oos.flush();
oos.close();
} catch (Exception e) {
}

   Like      Feedback     java.io.ByteArrayOutputStream  java.io  ObjectOutputStream


 Sample 13. Usage of java.nio.channels.FileLock

File lockF = new File(root, STORAGE_FILE_LOCK);
lockF.deleteOnExit();
RandomAccessFile file = new RandomAccessFile(lockF, "rws");
FileLock res = null;
try {
   res = file.getChannel().tryLock();
} catch(OverlappingFileLockException oe) {

}

   Like      Feedback     java.nio  FileLock  input output  file handling


 Sample 14. Code Sample / Example / Snippet of javax.naming.CompositeName

    public static void main(String[] args) throws Exception {

CompositeName c = new CompositeName("aaa/bbb");

java.io.FileOutputStream f1 = new java.io.FileOutputStream("/tmp/ser");

java.io.ObjectOutputStream s1 = new java.io.ObjectOutputStream(f1);

s1.writeObject(c);

s1.close();

java.io.FileInputStream f2 = new java.io.FileInputStream("/tmp/ser");

java.io.ObjectInputStream s2 = new java.io.ObjectInputStream(f2);

c = (CompositeName)s2.readObject();



System.out.println("Size: " + c.size());

System.out.println("Size: " + c.snit);

}


   Like      Feedback      javax.naming.CompositeName


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Code Sample / Example / Snippet of java.io.PrintWriter

  public Enumerable<Object[]> scan(DataContext root) {

final Random random = seed >= 0 ? new Random(seed) : new Random();

final Maze maze = new Maze(width, height);

final PrintWriter pw = new PrintWriter(System.out);

maze.layout(random, pw);

if (Maze.DEBUG) {

maze.print(pw, true);

}

return new AbstractEnumerable<Object[]>() {

public Enumerator<Object[]> enumerator() {

final Set<Integer> solutionSet;

if (solution) {

solutionSet = maze.solve(0, 0);

} else {

solutionSet = null;

}

return Linq4j.transform(maze.enumerator(solutionSet),

new Function1<String, Object[]>() {

public Object[] apply(String s) {

return new Object[] {s};

}

});

}

};

}


   Like      Feedback      java.io.PrintWriter


 Sample 16. Code Sample / Example / Snippet of java.io.File

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

final String directory = (String) operand.get("directory");

final File base =

(File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);

File directoryFile = new File(directory);

if (base != null && !directoryFile.isAbsolute()) {

directoryFile = new File(base, directory);

}

String flavorName = (String) operand.get("flavor");

CsvTable.Flavor flavor;

if (flavorName == null) {

flavor = CsvTable.Flavor.SCANNABLE;

} else {

flavor = CsvTable.Flavor.valueOf(flavorName.toUpperCase());

}

return new CsvSchema(directoryFile, flavor);

}


   Like      Feedback      java.io.File


 Sample 17. Code Sample / Example / Snippet of java.io.StringWriter

  public Fluent returns(Function<String, Void> checker) throws ParseException {

final Ast.Program program = parseProgram(pig);

final PigRelBuilder builder =

PigRelBuilder.create(PigRelBuilderTest.config().build());

final StringWriter sw = new StringWriter();

new CalciteHandler(builder, sw).handle(program);

checker.apply(Util.toLinux(sw.toString()));

return this;

}


   Like      Feedback      java.io.StringWriter


 Sample 18. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream

  private static Pair<SqlLine.Status, String> run(String... args)

throws Throwable {

SqlLine sqlline = new SqlLine();

ByteArrayOutputStream os = new ByteArrayOutputStream();

PrintStream sqllineOutputStream = new PrintStream(os);

sqlline.setOutputStream(sqllineOutputStream);

sqlline.setErrorStream(sqllineOutputStream);

SqlLine.Status status = SqlLine.Status.OK;



Bug.upgrade("[sqlline-35] Make Sqlline.begin public");



return Pair.of(status, os.toString("UTF8"));

}


   Like      Feedback      java.io.ByteArrayOutputStream


 Sample 19. Code Sample / Example / Snippet of java.io.BufferedWriter

  private void addThreadWriters(Integer threadId) {

StringWriter w = new StringWriter();

BufferedWriter bw = new BufferedWriter(w);

threadStringWriters.put(threadId, w);

threadBufferedWriters.put(threadId, bw);

threadResultsReaders.put(threadId, new ResultsReader(bw));

}


   Like      Feedback      java.io.BufferedWriter


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Code Sample / Example / Snippet of java.io.FileWriter

    private String createArtifact(String string) throws IOException {

File tmpFile = File.createTempFile("vap", "vm");

tmpFile.delete();

tmpFile.deleteOnExit();



FileWriter writer = new FileWriter(tmpFile);

writer.write(string);

writer.flush();

writer.close();



return tmpFile.toURI().toURL().toExternalForm();

}


   Like      Feedback      java.io.FileWriter


 Sample 21. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream

            public int compare(ResourceImpl r1, ResourceImpl r2) {

String s1 = getName(r1);

String s2 = getName(r2);

return s1.compareTo(s2);

}

});



Tag tag = doIndex(sorted);

if (repositoryFileName != null) {

ByteArrayOutputStream out = new ByteArrayOutputStream();


   Like      Feedback      java.io.ByteArrayOutputStream


 Sample 22. Code Sample / Example / Snippet of java.io.ByteArrayInputStream

    protected final void importSingleUser(Repository userRepository, String userName, String password) throws Exception {

ByteArrayInputStream bis = new ByteArrayInputStream((

"<roles>" +

"<user name="" + userName + "">" +

"<properties><username>" + userName + "</username></properties>" +

"<credentials><password type="String">" + password + "</password></credentials>" +

"</user>" +

"</roles>").getBytes());



Assert.assertTrue("Committing test user data failed!", userRepository.commit(bis, userRepository.getRange().getHigh()));

}


   Like      Feedback      java.io.ByteArrayInputStream


 Sample 23. Code Sample / Example / Snippet of java.io.Writer

    private File createFileWithContents(String name, String extension, String contents) throws IOException {

File file = File.createTempFile(name, extension);

file.deleteOnExit();

Writer w = new OutputStreamWriter(new FileOutputStream(file));

w.write(contents);

w.close();

return file;

}




   Like      Feedback      java.io.Writer


 Sample 24. Code Sample / Example / Snippet of java.io.FileOutputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Code Sample / Example / Snippet of java.io.FileInputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileInputStream


 Sample 26. Code Sample / Example / Snippet of java.io.OutputStream

    public static void generateBundle(ArtifactData data, Map<String, String> additionalHeaders) throws IOException {

OutputStream bundleStream = null;

try {

File dataFile = new File(data.getUrl().toURI());

OutputStream fileStream = new FileOutputStream(dataFile);

bundleStream = new JarOutputStream(fileStream, getBundleManifest(data.getSymbolicName(), data.getVersion(), additionalHeaders));

bundleStream.flush();

} catch (URISyntaxException e) {

throw new IOException();

} finally {

if (bundleStream != null) {

bundleStream.close();

}

}

}


   Like      Feedback      java.io.OutputStream


 Sample 27. Code Sample / Example / Snippet of java.io.BufferedReader

        public Object install(InputStream inputStream) throws Exception {

m_installCalled = true;

BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream));

String versionString = bufReader.readLine();

if (m_expectedInstallVersion.equals(new Version(versionString))) {

m_correctVersionInstalled = true;

}

return new Version(versionString);

}


   Like      Feedback      java.io.BufferedReader


 Sample 28. Code Sample / Example / Snippet of java.io.InputStream

    public static boolean filesDiffer(File first, File second) throws Exception {

if (first.length() != second.length()) {

return true;

}

InputStream firstStream = new FileInputStream(first);

InputStream secondStream = new FileInputStream(second);

try {

for (int i = 0; i < first.length(); i++) {

if (firstStream.read() != secondStream.read()) {

return false;

}

}

return true;

}

finally {

try {

firstStream.close();

}

finally {

secondStream.close();

}

}

}


   Like      Feedback      java.io.InputStream


 Sample 29. Code Sample / Example / Snippet of java.io.BufferedWriter

    public static File createTmpConfigOnDisk(String config) throws Exception {

File file = File.createTempFile("template", ".xml");

file.deleteOnExit();

BufferedWriter bw = new BufferedWriter(new FileWriter(file));

try {

bw.write(config);

return file;

}

finally {

bw.close();

}

}


   Like      Feedback      java.io.BufferedWriter


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Code Sample / Example / Snippet of java.io.File

    private ArtifactObject createArtifact(String name, Attributes attrs, InputStream is) throws Exception {

ArtifactObject artifact = findArtifact(name, attrs);



if (artifact != null) {

return artifact;

}

else if (Boolean.parseBoolean(attrs.getValue(DEPLOYMENT_PACKAGE_MISSING))) {

m_log.log(LogService.LOG_WARNING, String.format("Unable to create artifact '%s' as it is missing...", name));

return null;

}

else {

m_log.log(LogService.LOG_INFO, String.format("Creating artifact '%s'...", name));



File file = storeArtifactContents(name, is);

try {

return m_workspace.createArtifact(file.toURI().toURL().toExternalForm(), true /* upload */);

}

finally {

file.delete();

}

}

}


   Like      Feedback      java.io.File


 Sample 31. Write a program that reads file using FileReader and BufferedReader

File file = new File("/home/sample.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

   Like      Feedback     File handling  FileReader  BufferedReader


 Sample 32. Get the SQL Script from the file to String to be executed using JDBC

File file = new File("buggybread.txt"); // Create a File Handle
BufferedReader in = new BufferedReader(new FileReader(file)); // Get a Buffered Reader
LineNumberReader fileReader = new LineNumberReader(in); // Get a Line Number Reader
String str = JdbcTestUtils.readScript(fileReader, "--"); // Read the Script

   Like      Feedback     


 Sample 33. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter

String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];

List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);

File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
   csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);

   Like      Feedback     array of Strings  csv writer


 Sample 34. Get only files from a directory using FileFilter

File dir = new File("C:/Folder");

File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile();
}
});

   Like      Feedback     FileFilter



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner