I'm writing a little program that just takes a file, and trims the last 4 characters after a space and writes those to a new file. When I tell it to do this and then print them to console it works fine. They show up fine and everything works. But when I use the BufferedWriter to write it to a new file it gives me a weird string of characters in that file when I check it. Here is my code:
package trimmer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class trimmer {
private File file;
private File newfile;
private Scanner in;
public void Create() {
String temp, temp1;
try {
setScanner(new Scanner(file));
} catch (FileNotFoundException e) {
System.out.println("file not found!!");
}
if (!newfile.exists()) {
try {
newfile.createNewFile();
FileWriter fw = new FileWriter(newfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while (in.hasNextLine()) {
temp1 = in.nextLine();
temp = temp1.substring(temp1.lastIndexOf(' ') + 1);
System.out.println(temp);
bw.write(temp);
}
bw.close();
System.out.println("done!");
} catch (IOException e) {
System.out.println("Could not make new file: " + newfile + " Error code: " + e.getMessage());
}
}
}
public Scanner getScanner() {
return in;
}
public void setScanner(Scanner in) {
this.in = in;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public File getNewfile() {
return newfile;
}
public void setNewfile(File newfile) {
this.newfile = newfile;
}
}
and when I check the file it looks like this:
䐳噔吳商吳啍唳噎吳剄唳剄䘳剄唳噎吳商䠳卉䌳䕎䜳䱁䠳卉䴳㉕倳乓䐳䍐䐳啐吳䍖吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍䌳䕎䜳䱁䴳㉕倳乓䐳䍐䐳啐吳䍖䠳卉吳乓吳啍䔳䥘䌳噔匳剕唳乓唳䅍
Can anyone tell me why this would be happening?
FileWriter uses the platform default character encoding. If this is not the encoding that you want, then you need to use an OutputStreamWriter with the appropriately chosen character encoding.
Related
I have a data structure assignment were the code has to read the text data from a text file and print it onto the screen. The code that I wrote says that the build was a success but the text file itself doesn't print. What do I do?
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream
public class readFile{
public static void main(String[] args) throws IOException {
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
try{
fileByteStream = new FileInputStream("file1.txt");
file = new Scanner(fileByteStream);
while(file.hasNextInt()){
textFile = file.nextInt();
System.out.println("file1.txt");
}
}
catch(IOException e){
}
}
}
Replace System.out.println("file1.txt"); by System.out.println(textFile);.
This should work if you have the "file1.txt" saved in the correct location. As is, you are just passing the String "file1.txt" rather than the file object which was not yet created. (See line 13 of this code below)
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
public class readFile
{
public static void main(String[] args) throws IOException
{
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
File file1 = new File("file1.txt");
try
{
fileByteStream = new FileInputStream(file1);
file = new Scanner(fileByteStream);
System.out.println("Reading file...");
while(file.hasNextInt())
{
textFile = file.nextInt();
System.out.println(textFile);
System.out.println("Scanning a line..");
}
file.close();
}
catch(IOException e)
{
System.out.println("Exception handled");
e.printStackTrace();
}
}
}
You can use print statements to help see where the code is breaking. It looks like you have an IO Exception (input/output). Also, you should want to close the Scanner object.
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
public class readFile
{
public static void main(String[] args) throws IOException
{
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
try
{
fileByteStream = new FileInputStream("file1.txt");
file = new Scanner(fileByteStream);
System.out.println("Reading file...");
while(file.hasNextInt())
{
textFile = file.nextInt();
System.out.println(textFile);
System.out.println("Scanning a line..");
}
file.close();
}
catch(IOException e)
{
System.out.println("Exception handled");
}
}
}
I wrote a very simple piece of code, It was working perfectly since yesterday but now not working and even after lots of research/debugging i have not got the issue
import java.net.InetAddress;
import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class DetectLoggedInUser{
public static void returnUserName()
{
String computerName;
try {
File file =new File("d:\\TestFolder\\UsersloggedIn.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content= "\n UserName="+System.getProperty("user.name")+ " || Date and Time= "+new Date();
bufferWritter.write(content);
bufferWritter.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[])
{
returnUserName();
}
}
Now file is created but nothing is being written in file
Is there anything wrong with this code(keeping in mind it was working since yesterday)?
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
public class DetectLoggedInUser {
public static void returnUserName() {
try {
File file = new File("d:\\TestFolder\\UsersloggedIn.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content = "\n UserName=" + System.getProperty("user.name")
+ " || Date and Time= " + new Date();
bufferWritter.write(content);
bufferWritter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
returnUserName();
}
}
You can use
FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);
Instead of file.getName() in your code.File.getName() method returns only the name of the file or directory,not the absolute path;
You don't need to check if the files exists or not, beside that it works fine for me.
I am trying to create a file from a log report. To save the file I've created a button. When the button is pushed, the following code is executed:
public void SAVE_REPORT(KmaxWidget widget){//save
try {
String content = report.getProperty("TEXT");
File file = new File("logKMAX.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();
} catch (IOException e) {
e.printStackTrace();
}
} //SAVE_REPORT
I have no compilation errors, but there isn't any file saved.
Any idea on what might be wrong?
Use the new file API. For one, in your program, you don't verify the return value of .createNewFile(): it doesn't throw an exception on failure...
With the new file API, it is MUCH more simple:
public void saveReport(KmaxWidget widget)
throws IOException
{
final String content = report.getProperty("TEXT");
final Path path = Paths.get("logKMAX.txt");
try (
final BufferedWriter writer = Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.CREATE);
) {
writer.write(content);
writer.flush();
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class moveFolderAndFiles
{
public static void main(String[] args) throws Exception
{
File sourceFolder = new File("c:\\Audio Bible");
copyFolder(sourceFolder);
}
private static void copyFolder(File sourceFolder) throws Exception
{
File files[] = sourceFolder.listFiles();
int i = 0;
for (File file: files){
if(file.isDirectory()){
File filter[] = new File(file.getAbsolutePath()).listFiles();
for (File getIndividuals: filter){
System.out.println(i++ +"\t" +getIndividuals.getPath());
File des = new File("c:\\audio\\"+getIndividuals.getName());
Files.copy(getIndividuals.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}
Ok, I'm really confused by some code I wrote. It's a DataSetter (didn't know a better name for it...), and has methods to change the data in my data file (data.txt). This data has the following format: #key=value (eg. #version=1.0). Now, I tried to run this line of code:
new DataSetter().setValue("version", "1.1");
It just clears the file. That's pretty much all it does. Now, I think it clears the file because it makes a new File, which is completely empty but has the same name. Here's my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* This class contains methods to set specific data in the data.txt file. <br>
* The data is rewritten every time a new value is set.
*
* #author Casper van Battum
*
*/
public class DataSetter {
private static final File DATA_FILE = new File("resources/data.txt");
private static final String lineFormat = "#%s=%s";
private FileOutputStream out;
private DataReader reader = new DataReader();
private HashMap<String, String> dataMap = reader.getDataMap();
private Scanner scanner;
public DataSetter() {
try {
out = new FileOutputStream(DATA_FILE, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setValue(String key, String newValue) {
openDataFile();
String oldLine = String.format(lineFormat, key, dataMap.get(key));
dataMap.put(key, newValue);
String newLine = String.format(lineFormat, key, newValue);
try {
replace(oldLine, newLine);
} catch (IOException e) {
e.printStackTrace();
}
closeDataFile();
}
private void replace(String oldLine, String newLine) throws IOException {
ArrayList<String> tmpData = new ArrayList<String>();
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
tmpData.add((currentLine == oldLine) ? newLine : currentLine);
}
out.write(new String().getBytes());
String sep = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
for (String string : tmpData) {
sb.append(string + sep);
}
FileWriter writer = new FileWriter(DATA_FILE);
String outString = sb.toString();
writer.write(outString);
writer.close();
}
private void openDataFile() {
try {
scanner = new Scanner(DATA_FILE);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private void closeDataFile() {
scanner.close();
}
}
So after running the setValue() method, I just have an empty file...
Im really out of idea's on how to solve this...
You are truncating your data file with the
new FileOutputStream(DATA_FILE, false)
so no nothing is written when you go to output your the elements in the tmpData ArrayList read from Scanner.
ArrayList<String> tmpData = new ArrayList<String>();
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine(); // never gets called
...
}
The typical strategy for updating a text file is to create a temporary file with old file's contents (File#renameTo), write the data to file, then delete the temporary file after closing any open streams to the file being read.
I need to make a menu that list the .txt files in a directory. For example, if i have jonsmith12.txt , lenovo123.txt , dell123.txt in the directory how would I make an arraylist menu of:
Please choose one of the following:
jonsmith12
lenovo123
dell123
Please enter your choice:
I need an arraylist menu is because I don't know how many .txt files are in the directory at any given time.
import java.io.File;
public class ListFiles
{
public static void listRecord() {
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
}
}
}
}
}
Here is the class that will display the information in the .txt file onto the console. It stills need some modifying too but I could probably figure that out.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class DisplayRec {
public static void displayRecord() throws IOException {
File file = new File("williamguo5.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So the question is: How do I implement a ArrayList menu into my ListFiles class so it will display the .txt files.
You can use the alternate method signature for File.listFiles(FilenameFilter filter) to simplify your code:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
And unless you really enjoy writing loops, you don't even need to manually loop over the array to convert it to a List:
List<File> lstRecords = Arrays.asList(files);
Your displayRecord method was pretty close; you just needed to pass the file as an argument and use that instead of a hard-coded filename, and you needed to initialize dis.
Putting it all together:
package com.example.file;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FileExample {
public static List<File> listRecords(File dir) {
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
return Arrays.asList(files);
}
public static void displayRecord(File file) {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
String line = dis.readLine();
while (line != null) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(line);
line = dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
List<File> lstRecords = listRecords(new File("."));
for (File record : lstRecords) {
displayRecord(record);
}
}
}
It's also better to use Reader/Writer instead of InputStream/OutputStream if you're working with text files, and you should close your files in the finally block to avoid a potential resource leak.
You'll also notice I didn't explicitly use an ArrayList. In most cases, it's better to program against the interface (in this case, List) as much as possible, and only declare variables using the implementing class when you need to use a method that's only available to that class.
It looks like your sticking point above is the array. If you just need to iterate over the files in a directory, something as simple as the following will do the trick.
import java.io.File;
public class TxtEnumerator {
public static void main(String[] args) {
TxtEnumerator te = new TxtEnumerator();
te.listFiles();
}
public void listFiles() {
String filepath = "." + File.separator + "textDirectory";
File file = new File(filepath);
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (f.getName().endsWith(".txt")) {
System.out.println(f.getName());
}
}
}
}
}