Lists and Files - java

How to write a list in a file using JAVA?
I am writing a program to search files in a directory and display it. I also have a condition that I should store the search result in a log file. So please help me doing this.
From comments:
public void saveSearchResult(List<String> SearchResult) throws FileNotFoundException {
File file1 = new File("D://result.log");
FileInputStream in = new FileInputStream("D://result.log");
FileOutputStream out = new FileOutputStream(file1);
DataInputStream din = new DataInputStream(in);
DataOutputStream dout = new DataOutputStream(out);
for (String search : getSearchResult()) {
//Not getting hw to do this
}
}

Place your results into a string. Then load it into the file as follows...
StringBuilder s = new StringBuilder();
for (String search : getSearchResult()) {
s.append(search); //add formatting here as desired
}
try (FileWriter t = new FileWriter(new File("result.log"))) {
t.write(s.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
You should always use a try with resources statement as above because it will insure the resources are released. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
For a growing string you should use StringBuilder.
You probably want to create multiple new log files in which case I would suggest replacing "result.log" with this following code
new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss").format(new Date(
System.currentTimeMillis())) + ".log"
This will output your log files so it looks like this...
result_2014-02-13_5-19-44.log
year/month/day/hour/minute/second

Related

NoSuchFileException while reading a file

I am trying to read a file, but I get a NoSuchFileException. I know my code work, because it works in another program I have created, but it doesn't work now. Yes the directory is correct and there is a text file in the src folder. Please could someone tell me how to fix this.
String[] words = new String[5];
Path file = Paths.get("H:\\Varsity work\\Java Programming\\Programs\\HangMan\\build\\classes\\HangMan.txt");
InputStream input = null;
try {
input = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String s = null;
while((s=reader.readLine())!=null) {
System.out.println(s);
}
input.close();
} catch(Exception e) {
System.out.println(e);
}
try using '/' instead of '\' , so no need to escape any chars and path string used as is.

Appending a set with a text file

If I have a result stored in the following set:
Set<Integer> dataset = new HashSet<>();
Also, I have this text file:
File file = new File("\Users\Test.txt");
My goal is to append the set dataset with the Test.txt (Write it at the end of Test.txt or possibly append both to a new text file). I tried first to wrap my dataset using BufferedReader so I can prepare it for appending but I got stuck because the InputStreamReader does not accept Sets. I don't know how to fix it to proceed:
InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(dataset)); // Error Here
Thank you for any help.
You should proceed like this:
Set<Integer> dataset = new HashSet<>();
dataset.add(8);
dataset.add(3);
dataset.add(7);
try (FileWriter fw = new FileWriter("\\Users\\Test.txt", true); // true -> append
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
out.println(dataset);
} catch (IOException e) {
System.err.println("An exception occured: " + e.getMessage());
}
Note that we used a try with resources to automatically close the closable that were open in the try part.
I think there is an error in the path, you have to escape the '\':
File file = new File("\\Users\\Test.txt");

What is the simplest way to write a text file in Java?

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.

How to pass the contents of a file as parameters in ProcessBuilder

I want to pass a the contents of a .dat file as parameters in ProcessBuilder. How do I do this?
The .dat file contains:
08/10/12 4546.4 4644.5 6465.4 3 6.546 core dia,WH,C/C,no of steps,SF 0054.0 0005.0 005.00 0006.0 0006.0 066.00 0006.0 0006.0 006.00 leg width,yoke width,1/2 section step thk-Biggest size
I want to pass the content of the file as parameters in following code
ProcessBuilder processBuilder = new ProcessBuilder("E:\\MyFile.exe");
FileReader r = null;
try {
r = new FileReader(pathToDatFile);
char[] buf = new char[50000]; // Or whatever is a good max length.
int len = r.read(buf);
String content = new String(buf, 0, len);
String[] params = content.split(" ");
ArrayList<String> invocation = new ArrayList<String>();
invocation.add("E:\\MyFile.exe");
invocation.addAll(Arrays.asList(params));
ProcessBuilder processBuilder = new ProcessBuilder(invocation);
} catch (Exception e) {
// handle me!
} finally {
try { r.close(); } catch (Exception e) { /* handle me! */ }
}
Also: what encoding is your .dat file in? If it's not ASCII, you have to go via FileInputStream -> InputStreamReader so you can set the correct encoding in InputStreamReader. Otherwise, your code will use whatever the default is on the computer it happens to run on, with entertainingly inconsistent results!

Test if file exists

I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.
With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
why dont you just catch the FileNotFound exception and take that as the file not being present.
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.

Categories