I am trying to check if a file content is empty or not. I have a source file where the content is empty.
I tried different alternatives.But nothing is working for me.
Here is my code:
Path in = new Path(source);
/*
* Check if source is empty
*/
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br.readLine().length() == 0) {
/*
* Empty file
*/
System.out.println("In empty");
System.exit(0);
}
else{
System.out.println("not empty");
}
} catch (IOException e) {
e.printStackTrace();
}
I have tried using -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
All of the above is giving as not empty.And I need to use -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
Instead of new File() etc.
Please advice if I went wrong somewhere.
EDIT
Making little more clear. If I have a file with just whitespaces or
without white space,I am expecting my result as empty.
You could call File.length() (which Returns the length of the file denoted by this abstract pathname) and check that it isn't 0. Something like
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
To ignore white-space (as also being empty)
You could use Files.readAllLines(Path) and something like
static boolean isEmptyFile(String source) {
try {
for (String line : Files.readAllLines(Paths.get(source))) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Default to true.
return true;
}
InputStream is = new FileInputStream("myfile.txt");
if (is.read() == -1) {
// The file is empty!
} else {
// The file is NOT empty!
}
Of course you will need to close the is and catch IOException
You can try something like this:
A Utility class to handle the isEmptyFile check
package com.stackoverflow.answers.mapreduce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSOperations {
private HDFSOperations() {}
public static boolean isEmptyFile(Configuration configuration, Path filePath)
throws IOException {
FileSystem fileSystem = FileSystem.get(configuration);
if (hasNoLength(fileSystem, filePath))
return false;
return isEmptyFile(fileSystem, filePath);
}
public static boolean isEmptyFile(FileSystem fileSystem, Path filePath)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileSystem.open(filePath)));
String line = bufferedReader.readLine();
while (line != null) {
if (isNotWhitespace(line))
return false;
line = bufferedReader.readLine();
}
return true;
}
public static boolean hasNoLength(FileSystem fileSystem, Path filePath)
throws IOException {
return fileSystem.getFileStatus(filePath).getLen() == 0;
}
public static boolean isWhitespace(String str) {
if (str == null) {
return false;
}
int length = str.length();
for (int i = 0; i < length; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotWhitespace(String str) {
return !isWhitespace(str);
}
}
Class to test the Utility
package com.stackoverflow.answers.mapreduce;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
public class HDFSOperationsTest {
public static void main(String[] args) {
String fileName = "D:/tmp/source/expected.txt";
try {
Configuration configuration = new Configuration();
Path filePath = new Path(fileName);
System.out.println("isEmptyFile: "
+ HDFSOperations.isEmptyFile(configuration, filePath));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
Related
Hello everyone, Java beginner here. I am trying to run some java code in eclipse IDE, and set my args x = 25 from
Run > Run Configurations > Arguments > Apply > Run. However, before I can get to Arguments, I get this error message (see photo below). Does anyone know what this means or why I am getting this? What does this specific '.metadata/.plugins/org.eclipse.debug.core' do?
MY CODE BELOW:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class IOTest {
public IOTest () {
}
public void readFile () {
try {
FileReader file = new FileReader("movies.txt");
BufferedReader br = new BufferedReader(file);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("Unable to load file.");
}
}
public void writeFile () {
try {
FileWriter file = new FileWriter("tvshows.txt");
BufferedWriter bw = new BufferedWriter(file);
bw.write("Seinfeld\n");
bw.write("Breaking Bad\n");
bw.write("The Simpsons\n");
bw.write("Family Guy\n");
bw.close();
} catch (Exception e) {
System.out.println("Unable to load/create file.");
}
}
public static void main(String[] args) {
IOTest test = new IOTest();
test.readFile();
test.writeFile();
if (args.length == 1) {
// Do something.
int x = Integer.parseInt(args[0]);
System.out.println("x = " + x);
} else {
// Do something else.
}
}
}
im really struggling one this one. Basically im working with a couple of my classmates to a project where we have to deliver a space wars remake and we implemented a single player mode where you can actually get scores. problem is i can read my file but cannot write on it. ive tryed with all the system i could find online but didn't manage to get the error solved. here is the code of the class that manages the highscore system. i even tryed creating the file with code and tryed deleting it and recreating an empty one. the file is in the home directory of the project right now. the metods readFile and getHighscores work but the check one always gets stuck in the writing part.
the error i get is " Il privilegio richiesto non appartiene al client
[Ljava.lang.StackTraceElement;#6eb60ef7"
which translates in "The requested privilege does not belong to the client"
Keep in mind it's all in a git repository where i should have all the permissions but it's basically the only idea left in my mind.
package controller;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
*the creation of the HighscoreManager class.
*/
public class HighscoreManager {
private static final int LAST_HIGHSCORE_INDEX = 9;
private static final String FILE_NAME = "/Highscores.txt";
private ArrayList<Integer> highscores = new ArrayList<Integer>();
/**
* reads the file and loads the highscore list.
*/
private void readFile() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
String s;
highscores.clear();
try {
is = this.getClass().getResourceAsStream(FILE_NAME);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((s = br.readLine()) != null) {
highscores.add(Integer.parseInt(s));
}
if(br!=null && isr !=null && is!= null) {
br.close();
isr.close();
is.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* checks if the passed score is an actual highscores.
* #param score
*/
public void checkHighscores(final int score) {
readFile();
File file = new File(FILE_NAME);
boolean newHighscoreFound = false;
for (int i = 0; i < highscores.size(); i++) {
if (score > highscores.get(i)) {
newHighscoreFound = true;
break;
}
}
if (newHighscoreFound) {
highscores.add(LAST_HIGHSCORE_INDEX, score);
Collections.sort(highscores);
Collections.reverse(highscores);
for (int i : highscores) {
System.out.println(i);
}
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
for(int i : highscores) {
bw.write(i);
}
} catch(IOException e) {
System.out.println(e.getStackTrace());
} finally {
if(fw != null && bw != null) {
try {
fw.close();
bw.close();
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}
}
}
}
/**
* returns an array list of strings containing all the current highscores.
* #return toBeReturned
*/
public ArrayList<String> getHighscores() {
ArrayList<String> toBeReturned = new ArrayList<>();
try {
highscores.clear();
readFile();
for (int i : highscores) {
toBeReturned.add(String.valueOf(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("There you have your highscores.");
}
return toBeReturned;
}
}
You don't need to access the Class object to load a file (or indeed the associated ClassLoader). Just use normal Java IO.
To read your set of high scores:
highScores = Files.lines(Paths.get(FILE_NAME))
.map(Integer::parseInt)
.collect(Collectors.toList());
To write a new set of high scores:
Files.write(Paths.get(FILE_NAME), highScores.stream()
.map(String::valueOf)
.collect(Collectors.toList()));
(Also, why is this tagged with "git"?)
I am trying to add a new property to config.properties if it isn't there. Is there any way to do this?
My current config class looks like this:
package com.template;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class Config {
static File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template");
public static void add() {
if(!folder.exists()) {
try {
folder.mkdirs();
} catch(SecurityException e) {
Log.error(e);
}
}
Properties config = new Properties();
OutputStream output = null;
Path filePath = Paths.get(folder + "/config.properties");
if(!(filePath == null)) {
try {
output = new FileOutputStream(folder + "/config.properties");
config.setProperty("log", "true");
config.store(output, null);
} catch(IOException e) {
Log.error(e);
} finally {
if(output !=null) {
try {
output.close();
} catch(IOException e) {
Log.error(e);
}
}
}
}
}
public static String get(String value) {
Properties config = new Properties();
InputStream input = null;
try {
input = new FileInputStream(folder + "/config.properties");
config.load(input);
} catch(IOException e) {
Log.error(e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return config.getProperty(value).trim();
}
}
This is working, as it won't overwrite the file if you edit it, but if you delete an entry, you need to completely delete the whole file to re-add that entry.
My ultimate goal is for you to be able to close the program, edit the config file, then reopen the config file with the new arguments, but if you delete an argument, it won't crash to program because it relies on an answer from the config file. (I hope that makes sense. It's basically like most video games).
You need to validate the value you get from the Properties before using it. e.g. you can't .trim() a value which wasn't here.
public class Config {
static final File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template");
static final File file = new File(folder, "config.properties");
public static void add() throws IOException {
if (file.exists())
return;
// create directories as needed.
folder.mkdirs();
Properties config = new Properties();
config.setProperty("log", "true");
try (OutputStream out = new FileOutputStream(file)) {
config.store(out, null);
}
}
public static String get(String key, String defaultValue) {
if (!file.exists())
return defaultValue;
try (InputStream in = new FileInputStream(file)) {
Properties config = new Properties();
config.load(input);
} catch(IOException e) {
Log.error(e);
return defaultValue;
}
String value = config.getProperty(key);
if (value == null)
return defaultValue;
value = value.trim();
if (value.isEmpty())
return defaultValue;
return value;
}
}
I am changing names of all files in directory and if it's text file I am changing the content but it doesn't seem to work the name of the file is changed right but content is blank/gone heres is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is several issue with your code:
Your rewrite function is perform on old name File. It should be done on the renamed File:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
you are trying to read docx and pdf file like regular text file. This cannot work. You will have to use external library like POI and pdf Box
Your rewrite function is not safe. You must unsure to close the ressources:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}
You can't re-write a file on top of itself. you need to write the new content to a new file, then rename again.
The file begins with about 200 lines of background information that i don't need. Im trying to skip/ignore those 200 lines until a string is found. Once this string is found I want to be able to continue processing the rest of the text file.
Sample Text File:
(up to around line 240 is all the lines i need to skip/ignore)
http://pastebin.com/5Ay4ad6y
public static void main(String args[]) {
String endOfSyllabus = "~ End of Syllabus";
Path objPath = Paths.get("2014HamTechnician.txt");
if (Files.exists(objPath)) {
File objFile = objPath.toFile();
try (BufferedReader in = new BufferedReader(new FileReader(objFile))) {
String line = in.readLine();
while (line != null) {
line = in.readLine();
}
if(endOfSyllabus.equals(line) ){
restOfTextFile = line.split(endOfSyllabus);
}
}
System.out.println(restOfTextFile[0]);
}
catch(IOException e){
System.out.println(e);
}
}
else{
System.out.println(
objPath.toAbsolutePath() + " doesn't exist");
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new A19015_Form().setVisible(true);
}
});
}
You can try this if you know the exact string that you are looking
if (lineString.startsWith("insert exact string")) {
// ...
}
What about:
boolean found = false;
for (String line; (line = in.readLine()) != null;) {
found = found || line.equals(endOfSyllabus);
if (found) {
// process line
}
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
List<String> lines = FileUtils.readLines(new File("test.txt"));
List<String> avLines = new ArrayList<>();
boolean valid = false;
for (String line : lines) {
if (line.trim().equals("~ End of Syllabus")) {
valid = true;
continue;
}
if (valid) {
avLines.add("\n"+line);
}
}
System.out.println(avLines.size());
}
}