simple: how do i read the contents of a directory in Java, and save that data in an array or variable of some sort? secondly, how do i open an external file in Java?
You can use java IO API. Specifically java.io.File, java.io.BufferedReader, java.io.BufferedWriter etc.
Assuming by opening you mean opening file for reading. Also for good understanding of Java I/O functionalities check out this link: http://download.oracle.com/javase/tutorial/essential/io/
Check the below code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileIO
{
public static void main(String[] args)
{
File file = new File("c:/temp/");
// Reading directory contents
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
// Reading conetent
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("c:/temp/test.txt"));
String line = null;
while(true)
{
line = reader.readLine();
if(line == null)
break;
System.out.println(line);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(reader != null)
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
You can use a class java.io.File to do that. A File is an abstract representation of file and directory pathnames. You can retrieve the list of files/directories within it using the File.list() method.
There's also the Commons IO package which has a variety of methods for manipulating files and directories.
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
public class CommonsIO
{
public static void main( String[] args )
{
// Read the contents of a file into a String
try {
String contents = FileUtils.readFileToString( new File( "/etc/mtab" ) );
} catch (IOException e) {
e.printStackTrace();
}
// Get a Collection of files in a directory without looking in subdirectories
Collection<File> files = FileUtils.listFiles( new File( "/home/ross/tmp" ), FileFilterUtils.trueFileFilter(), null );
for ( File f : files ) {
System.out.println( f.getName() );
}
}
}
public class StackOverflow {
public static void main(String[] sr) throws IOException{
//Read a folder and files in it
File f = new File("D:/workspace");
if(!f.exists())
System.out.println("No File/Dir");
if(f.isDirectory()){// a directory!
for(File file :f.listFiles()){
System.out.println(file.getName());
}
}
//Read a file an save content to a StringBuiilder
File f1 = new File("D:/workspace/so.txt");
BufferedReader br = new BufferedReader(new FileReader(f1));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
sb.append(line+"\n");
System.out.println(sb);
}
}
Related
I want to open, read, and edit file from my desktop. I am using Ideone online compiler. How do I read the file? I tried the following code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
class demo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
File file = new File("C:/Users/psanghavi/Desktop/admin_confirmation_original.txt");
if (!file.exists())
{
System.out.println("does not exist.");
return;
}
if (!(file.isFile() && file.canRead()))
{
System.out.println(file.getName() + " cannot be read from.");
return;
}
try
{
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0)
{
current = (char) fis.read();
System.out.print(current);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
My desktop has file named: admin_confirmation_original.txt
Currently, No. About the limit, Idebone FAQ say about this:
Can I write or read files in my program? - No
Can I access the network from my program? - No
You can learn more about many Ideone restricted rule at FAQ.
Ideoone doesn't support reading local files.
This is not an answer to your question, but wrt to the comments
if you want to read files hosted, you could access them using URL class.
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Demo {
public static void main(String[] args) throws IOException {
try {
final URL url = new URL("http://www.google.co.in/robots.txt");
//URL url = new URL("http://74.125.236.52/robots.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while (in.readLine() != null) {
str = in.readLine();
System.out.println(str);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I have not tried it on file hosting sites.There are a lot of free file hostings available just google it.
How can i load a text file with a runnable .jar file, It works fine when it's not jarred but after i jar the application it can't locate the file. Here's what i'm using to load the text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PriceManager {
private static Map<Integer, Double> itemPrices = new HashMap<Integer, Double>();
public static void init() throws IOException {
final BufferedReader file = new BufferedReader(new FileReader("prices.txt"));
try {
while (true) {
final String line = file.readLine();
if (line == null) {
break;
}
if (line.startsWith("//")) {
continue;
}
final String[] valuesArray = line.split(" - ");
itemPrices.put(Integer.valueOf(valuesArray[0]), Double.valueOf(valuesArray[1]));
}
System.out.println("Successfully loaded "+itemPrices.size()+" item prices.");
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
file.close();
}
}
}
public static double getPrice(final int itemId) {
try {
return itemPrices.get(itemId);
} catch (final Exception e) {
return 1;
}
}
}
Thanks for any and all help.
There are two reasons for this. Either the file is now embedded within the Jar or it's not...
Assuming that the file is not stored within the Jar, you can use something like...
try (BufferedReader br = new BufferedReader(new InputStreamReader(PriceManager.class.getResourceAsStream("/prices.txt")))) {...
If the prices.txt file is buried with the package structure, you will need to provide that path from the top/default package to where the file is stored.
If the file is external to the class/jar file, then you need to make sure it resides within the same directory that you are executing the jar from.
if this is your package structure:
Correct way of retrieving resources inside runnable or.jar file is by using getResourceAsStream.
InputStream resourceStream = TestResource.class.getResourceAsStream("/resources/PUT_Request_ER.xml");
If you do getResource("/resources/PUT_Request_ER.xml"), you get FileNotFoundException as this resource is inside compressed file and absolute file path doesn't help here.
Today I encountered problems to launch a jar-file for the first time. Now I know (after unzipping the jar) that the textfiles did not come along when I did the export and creation of a jar-package of my program in Eclipse.
Why does the textfiles not come along with the class files? Where should I put those in the project?
I put the textfiles in the root of the project folder
Greaful for help
EDIT: probably I can do it manually in the cmd but I dont know what I should add in the programcode where the textfiles are loaded. Should I for instance impelent a classloader?
I know how to do so when loading images such as jpg org gif. But what if it is a textfile?
Here is the method responsible for loading textfiles
private void read(String text_file, int len, int index) {
String[] stringBuffer = new String[len];
File file = new File(text_file);
FileReader fileReader;
BufferedReader bufferedReader ;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
int i = 0;
while ( (line = bufferedReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
bufferedReader.close();
} catch (FileNotFoundException fnde) {
fnde.printStackTrace();
JOptionPane.showMessageDialog(null, "files could not be found", "Help", 0);
} catch (Exception e) {
e.printStackTrace();
}
splitString(stringBuffer, index);
}
I made an example from your code. The file text.txt is in the source folder under META-INF.
package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class ReadFile {
public static void main(String[] args) {
ReadFile o = new ReadFile();
o.read("test.txt", 2, 0);
}
private void read(String text_file, int len, int index) {
BufferedReader bufferedReader ;
String[] stringBuffer = new String[len];
try {
bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/META-INF/".concat(text_file))));
String line;
int i = 0;
while ( (line = bufferedReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
bufferedReader.close();
} catch (FileNotFoundException fnde) {
fnde.printStackTrace();
JOptionPane.showMessageDialog(null, "files could not be found", "Help", 0);
} catch (Exception e) {
e.printStackTrace();
}
splitString(stringBuffer, index);
}
private void splitString(String[] stringBuffer, int index) {
for(String line: stringBuffer) {
System.out.println(line);
}
}
}
Hope this helps.
Only folders/jars listed under -> Properties -> Java Build Path -> Order and Export will be exported into the JAR. Place the files into a folder, which is on your build path by
adding any folder as source folder ( -> Properties -> Java Build Path -> Source)
or putting the file into a sub-folder of your standard src folder.
the base folder of your project is not and should/can not be part of the export.
I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
I am trying to store string of array in a text file and read it. But I can't get it working. I am getting NullPointerError.
Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at in.isuru.justconverter.FileDbTool.readFile(FileDbTool.java:41)
at in.isuru.justconverter.Test.main(Test.java:10)
Here's two classes.
package in.isuru.justconverter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class FileDbTool {
File dataFile;
ArrayList<String> filePath;
public void checkFile(){
dataFile = new File("db.txt");
if(dataFile.exists()){
readFile();
}else{
try {
dataFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Coudn't Create New File!");
System.exit(1);
}
}
}
public void readFile(){
int len;
try{
char[] chr = new char[4096];
StringBuffer buffer = new StringBuffer();
FileReader reader = new FileReader(dataFile);
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
}finally {
reader.close();
}
System.out.println(buffer.toString());
StringTokenizer st = new StringTokenizer(buffer.toString(), ",");
while (st.hasMoreTokens()) {
String value = st.nextToken();
filePath = null;
filePath = new ArrayList<String>();
filePath.add(value);
}
}catch(IOException e){
JOptionPane.showMessageDialog(null, "Read Error");
}
}
public String[] getFilePathArray(){
readFile();
return filePath.toArray(new String[filePath.size()]);
}
public File[] getFiles(){
String[] paths = getFilePathArray();
ArrayList<File> files = new ArrayList<File>();
for(int i = 0; i < paths.length; i++){
File file = new File(paths[i]);
files.add(file);
}
return files.toArray(new File[files.size()]);
}
public void eraseFile(){
dataFile.delete();
}
public void writeFile(String[] stuff){
try{
BufferedWriter out = new BufferedWriter(new FileWriter(dataFile, true));
out.append(stuff + ",");
}catch(IOException e){
}
}
public void writeToDb(String[] array){
writeFile(array);
}
}
And main class
package in.isuru.justconverter;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
FileDbTool app = new FileDbTool();
app.checkFile();
}
}
Well this is a portion of a swing program. I am trying to use text file as a small database.
Line 41 is this:
FileReader reader = new FileReader(dataFile);
so I'd wager that dataFile is null here.
However, you do seem to initialize it before calling this method, otherwise the exception would be thrown inside checkFile.
Are you sure you are not calling readFile directly somewhere without calling checkFile first? In any case, this pattern is not a recommended approach, because you are requiring the users of your class to call methods in a specific order.
From the stack trace , it seems like you called readfile() directly from main rather than through checkfile() . So dataFile is null since it is not initialized by checkfile . Also the stack trace and the given code doesn't match . When FileReader constructor is called with null argument , it will throw NullPointerException when it reaches FileInputstream constructor .
Here is the code from jdk source :
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
open(name);
}