Get file contents in java

How to get file content in java

Solution: You can download the file, save it and then use the following: This should give you the content type. When reading through Java code, how to get content type of file?

How to get file content in java

My question is how to get file content in class File (java )

File folder = new File("BitTorrent"); for (final File SubFile : folder.listFiles()) < if (!SubFile.isDirectory()) < **// HOW TO READ ALL THE CONTENT OF SUBFILE WITHOUT USING ITS PATH.** >> 

What I mean is that are there any get method can do this. We can use these codes below instead, but I don’t like that

Path p = Paths.get(file.getAbsolutePath()); byte[] fileArray = Files.readAllBytes(p); 

Thanks for your help in advance.

Without using the path of the file as here :

Path p = Paths.get(file.getAbsolutePath()); byte[] fileArray = Files.readAllBytes(p); 

you can open a DataInputStream and read all the content in a byte array :

File folder = new File("BitTorrent"); for (final File SubFile : folder.listFiles()) < if (!SubFile.isDirectory()) < **// HOW TO READ ALL THE CONTENT OF SUBFILE WITHOUT USING ITS PATH.** byte[] bytes= new byte[(int)SubFile.length()]; DataInputStream dataIs = new DataInputStream(new FileInputStream(SubFile)); dataIs.readFully(bytes); // here bytes has the content >> 

How to get file content in java?, to get the content of a txt file I usually use a scanner and iterate over each line to get the content: Scanner sc = new Scanner(new File(«file.txt»)); while(sc.hasNextLine()) < String str = sc.nextLine(); >Does the java api provide a way to get the content with one line of code like: Code samplepublic static void main(String[] args) throws IOException Feedback

Читайте также:  Responsive web design with html5 and css pdf

Get content file in java

I used this method to download and get content type

 @GetMapping("/downloadFile/") public ResponseEntity downloadFile(@RequestParam String fileName, HttpServletRequest request) < // Load file as Resource Resource resource = fileStorageService.loadOneFileAsResource(fileName); // Try to determine file's content type String contentType = null; try < contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); >catch (IOException ex) < logger.info("Could not determine file type."); >// Fallback to the default content type if type could not be determined if(contentType == null) < contentType = "application/octet-stream"; >return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); > 

But always detect my content «application/octet-stream», what is problem and what should I do? thanks in advance.

You can download the file, save it and then use the following:

Path path = Paths.get(resource.getURI()); String contentType = Files.probeContentType(path); 

This should give you the content type. Look over here.

How to get file content in java, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

How to get content type of a file which has no extension? [duplicate]

I have saved all types of file without extension. When reading through Java code , how to get content type of file?

File file = "/admin/sun" byte[] pdfByteArray = FileUtils.readFileToByteArray(file); if (fileName.endsWith(".pdf")) < response.setContentType("application/pdf"); >else < response.setContentType("image/jpeg"); >response.getOutputStream().write(pdfByteArray); response.getOutputStream().flush(); 

What is if the file extension .pdf or .jpeg it is working then without Extension How to get content -type?

Use Files.probeContentType(path) in jdk7. Or detect the file type yourself, according to different file type specifications . Say pdf http://www.adobe.com/devnet/pdf/pdf_reference.html

You better do not rely on extensions. Find the mime type of the file.

See this SO question: Getting A File’s Mime Type In Java

You must read the mime type with Files.probeContentType(path) .

More relevant information on mime types

Spring boot — get content file in java, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Get the content of MultipartFile

I am trying to get the content of MultipartFile , which is obtained through MultipartHttpServletRequest.getFile() .

There are 2 functions in MultipartFile :

What is the most efficient way to get the content? (Which method would you use?)

Only difference is that with getBytes() the data has already been read from the stream, whereas with getinputstream () you will still have to read the data.

What you use depends on what you want to do with the content. If its an image that you just want to write out to disk, then getBytes() would be best, but if it is Text that you want to parse and do something with, then getinputstream() might be better.

How to Read a File in Java, The many ways to write data to File using Java. 2. Setup. 2.1. Input File. In most examples throughout this article, we’ll read a text file with filename …

Источник

Java read file to String

Java read file to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometimes while working with files, we need to read the file to String in Java. Today we will look into various ways to read the file to String in Java.

Java read file to String

  1. Java read file to String using BufferedReader
  2. Read file to String in java using FileInputStream
  3. Java read file to string using Files class
  4. Read file to String using Scanner class
  5. Java read file to string using Apache Commons IO FileUtils class

java read file to string

Now let’s look into these classes and read a file to String.

Java read file to String using BufferedReader

We can use BufferedReader readLine method to read a file line by line. All we have to do is append these to a StringBuilder object with newline character. Below is the code snippet to read the file to String using BufferedReader.

BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); String line = null; String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) < stringBuilder.append(line); stringBuilder.append(ls); >// delete the last new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close(); String content = stringBuilder.toString(); 

There is another efficient way to read file to String using BufferedReader and char array.

BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; while (reader.read(buffer) != -1) < stringBuilder.append(new String(buffer)); buffer = new char[10]; >reader.close(); String content = stringBuilder.toString(); 

Read file to String in java using FileInputStream

We can use FileInputStream and byte array to read file to String. You should use this method to read non-char based files such as image, video etc.

FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); while (fis.read(buffer) != -1) < sb.append(new String(buffer)); buffer = new byte[10]; >fis.close(); String content = sb.toString(); 

Java read file to string using Files class

We can use Files utility class to read all the file content to string in a single line of code.

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

Read file to String using Scanner class

The scanner class is a quick way to read a text file to string in java.

Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); String content = scanner.useDelimiter("\\A").next(); scanner.close(); 

Java read file to string using Apache Commons IO FileUtils class

If you are using Apache Commons IO in your project, then this is a simple and quick way to read the file to string in java.

String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); 

Java read file to String example

Here is the final program with proper exception handling and showing all the different ways to read a file to string.

package com.journaldev.files; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import org.apache.commons.io.FileUtils; public class JavaReadFileToString < /** * This class shows different ways to read complete file contents to String * * @param args * @throws IOException */ public static void main(String[] args) < String fileName = "/Users/pankaj/Downloads/myfile.txt"; String contents = readUsingScanner(fileName); System.out.println("*****Read File to String Using Scanner*****\n" + contents); contents = readUsingApacheCommonsIO(fileName); System.out.println("*****Read File to String Using Apache Commons IO FileUtils*****\n" + contents); contents = readUsingFiles(fileName); System.out.println("*****Read File to String Using Files Class*****\n" + contents); contents = readUsingBufferedReader(fileName); System.out.println("*****Read File to String Using BufferedReader*****\n" + contents); contents = readUsingBufferedReaderCharArray(fileName); System.out.println("*****Read File to String Using BufferedReader and char array*****\n" + contents); contents = readUsingFileInputStream(fileName); System.out.println("*****Read File to String Using FileInputStream*****\n" + contents); >private static String readUsingBufferedReaderCharArray(String fileName) < BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; try < reader = new BufferedReader(new FileReader(fileName)); while (reader.read(buffer) != -1) < stringBuilder.append(new String(buffer)); buffer = new char[10]; >> catch (IOException e) < e.printStackTrace(); >finally < if (reader != null) try < reader.close(); >catch (IOException e) < e.printStackTrace(); >> return stringBuilder.toString(); > private static String readUsingFileInputStream(String fileName) < FileInputStream fis = null; byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); try < fis = new FileInputStream(fileName); while (fis.read(buffer) != -1) < sb.append(new String(buffer)); buffer = new byte[10]; >fis.close(); > catch (IOException e) < e.printStackTrace(); >finally < if (fis != null) try < fis.close(); >catch (IOException e) < e.printStackTrace(); >> return sb.toString(); > private static String readUsingBufferedReader(String fileName) < BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); try < reader = new BufferedReader(new FileReader(fileName)); String line = null; String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) < stringBuilder.append(line); stringBuilder.append(ls); >// delete the last ls stringBuilder.deleteCharAt(stringBuilder.length() - 1); > catch (IOException e) < e.printStackTrace(); >finally < if (reader != null) try < reader.close(); >catch (IOException e) < e.printStackTrace(); >> return stringBuilder.toString(); > private static String readUsingFiles(String fileName) < try < return new String(Files.readAllBytes(Paths.get(fileName))); >catch (IOException e) < e.printStackTrace(); return null; >> private static String readUsingApacheCommonsIO(String fileName) < try < return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); >catch (IOException e) < e.printStackTrace(); return null; >> private static String readUsingScanner(String fileName) < Scanner scanner = null; try < scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); // we can use Delimiter regex as "\\A", "\\Z" or "\\z" String data = scanner.useDelimiter("\\A").next(); return data; >catch (IOException e) < e.printStackTrace(); return null; >finally < if (scanner != null) scanner.close(); >> > 

You can use any of the above ways to read file content to string in java. However, it’s not advisable if the file size is huge because you might face out of memory errors.

You can checkout more Java IO examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью