I am trying to create a new file directory, but the function mkdir() doesn't work, neither mkdirs().
Here's my code:
...
while (leitor.hasNext()){
String [] plv = LerPalavras(tamMem, leitor);
Arrays.sort(plv);
String nomeTemp = "/temp/temp" + contador + ".txt"; // I need to create this directory
try{
escritor = new FileWriter(nomeTemp);
for (int i = 0; i < tamMem; i++) {
escritor.write(plv[i] + " ");
}
escritor.close();
} catch (IOException e){
System.out.println(e.getMessage());
}
contador++;
}
...
Edit: I made the edits and now it's working!
File pastaTemp = new File("/temp/temp");
pastaTemp.mkdirs();
while (leitor.hasNext()){
String [] plv = LerPalavras(tamMem, leitor);
Arrays.sort(plv);
File arqTemp = new File (pastaTemp, contador + ".txt");
try{
escritor = new FileWriter(arqTemp);
for (int i = 0; i < tamMem; i++) {
escritor.write(plv[i] + " ");
}
escritor.close();
} catch (IOException e){
System.out.println(e.getMessage());
}
contador++;
}
Try doing this in two steps. First, call File.mkdirs() to create the entire directory structure, if necessary, then create the file you pass to the FileWriter:
try {
File folder = new File("/temp/temp");
folder.mkdirs();
// then create a file object at this location
File file = new File(folder, contador + ".txt");
escritor = new FileWriter(file);
// the rest of your code
}
catch (Exception e) {
}
Related
I am designing a program that saves the index location for specific characters from a message. Then, I need to retrieve these characters according to their index location. I kept the locations for these characters in a .txt file. I retrieved them, but at the end, I got this message "Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 120 out of bounds for length 120".
My codes:
int n;
String s;
int lineNumCount = 0;
String coverText = stegoMsg.getText(); // get the stego text from the textfield
int k = coverText.length(); // get the length for the stego text
int lineNumb = 1;
Scanner myFile = null;
try{
Scanner file = new Scanner(new File("location.txt"));//location.txt is the file that has the locations for the characters
myFile = file;
}catch (FileNotFoundException e){
System.out.println("File does not found");
}
while (myFile.hasNextLine()){
//Count the Number of the lines in location.txt
//1. Read the File
File fileLocation = new File("location.txt");
if(fileLocation.exists()){
try {
FileReader fr = new FileReader(fileLocation);
LineNumberReader lr = new LineNumberReader(fr); //2. Read the lines for location.txt
while((lr.readLine()) !=null){
lineNumCount++;
}
// System.out.println("Total Number of the Lines " + lineNumCount);
} catch (FileNotFoundException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
}
for(int x = 0; x<lineNumCount; ++x){
try{
String line = Files.readAllLines(Paths.get("location.txt")).get(lineNumb);
// System.out.println("Line First " + line);
BufferedReader bufrd = new BufferedReader(new FileReader("SFile.txt")); //SFile.txt is the file that has the messsage that I need to take the location for the specific characters
int nn = Integer.parseInt(line);
s = bufrd.readLine();
System.out.println("The Location " + nn + " is : "+ s.charAt(nn)); // read the character that has this location
lineNumb++;
}catch(IOException e){
System.out.println("Line 334");
}
}
}
}
myFile.close();
}
Is it possible to guide me on how I can solve the exception?
I appreciate any help you can provide.
Here is the solution ...
int n;
String s;
int lineNumCount = 0;
String coverText = stegoMsg.getText(); // get the stego text from the textfield
int k = coverText.length(); // get the length for the stego text
int lineNumb = 1;
Scanner myFile = null;
try{
Scanner file = new Scanner(new File("location.txt"));
myFile = file;
}catch (FileNotFoundException e){
System.out.println("File does not found");
}
try{
while (myFile.hasNext()){
//Count the Number of the lines in location.txt
//1. Read the File
File fileLocation = new File("C:\\Users\\Farah\\Dropbox\\Steganography codes\\NewStegoTech\\location.txt");
if(fileLocation.exists()){
try {
FileReader fr = new FileReader(fileLocation);
LineNumberReader lr = new LineNumberReader(fr); //2. Read the lines for location.txt
while((lr.readLine()) !=null){
lineNumCount++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
}
try{
String line = Files.readAllLines(Paths.get("location.txt")).get(lineNumb);
// System.out.println("Line First " + line);
BufferedReader bufrd = new BufferedReader(new FileReader("Stego File.txt"));
int nn = Integer.parseInt(line);
s = bufrd.readLine();
System.out.println("The Loocation " + nn + " is : "+ s.charAt(nn)); // read the character that has this location
lineNumb++;
}catch(IOException e){
System.out.println(e);
}
}
}
}catch(IndexOutOfBoundsException e)
{
System.out.println("Finish reading file");
}
myFile.close();
i am having some problem in java, i wanted to remove number 5 to number 7 and save them into a new file called RevisedNumbers.txt, is there any way to do that? this is my code so far
import java.util.Scanner;
import java.io.*;
public class Txt {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File myObj = new File("Numbers1to10.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
Writer writer = new PrintWriter("Numbers1to10.txt");
for(int i = 1; i <= 10; i++)
{
writer.write("Number" + i);
writer.write("\r\n");
}
writer.close();
File readFile = new File("Numbers1to10.txt");
Scanner read = new Scanner(readFile);
while (read.hasNextLine())
System.out.println(read.nextLine());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
File myObj = new File("RevisedNumbers.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
the desired output on the new file will be
Number 1
Number 2
Number 3
Number 4
Number 8
Number 9
Number 10
One possible solution might be using an additional file.
While reading the contents of the first file ("Numbers1to10.txt"), if values are within 5 to 7, then write it into the second file ("RevisedNumbers.txt"), otherwise write it into the additional file.
Now the additional file contains values that you need in the first file. So copy all contents of the additional file into the first file.
Here is a sample code.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWriteMain {
static void _write1to10(String locationWithFileName) {
try {
File file = new File(locationWithFileName);
boolean fileAlreadyExist = file.exists();
if (fileAlreadyExist) {
System.out.println("File already exists!");
} else {
System.out.println("New file has been created.");
}
FileWriter fileWriter = new FileWriter(file);
for (int i = 1; i <= 10; i++) {
fileWriter.write("Number " + i);
fileWriter.append('\n');
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static File _getFile(String locationWithFileName) {
File file = null;
file = new File(locationWithFileName);
return file;
}
// it reads a file and print it's content in console
static void _readFile(Scanner scanner) {
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
System.out.println(currLine);
}
}
// read contents from sourceFile file and copy it into destinationFile
static void _copyFromOneFileToAnother(File sourceFile, File destinationFile) throws IOException {
FileWriter destFileWriter = new FileWriter(destinationFile);
Scanner scanner = new Scanner(sourceFile);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
destFileWriter.write(currLine);
destFileWriter.append('\n');
}
destFileWriter.close();
}
public static void main(String[] args) {
String locationWithFileName = "E:\\FileWriteDemo\\src\\Numbers1to10.txt"; // give your file name including it's location
_write1to10(locationWithFileName);
System.out.println("File writing done!");
File file1 = _getFile(locationWithFileName);
try {
// creating file 2
String locationWithFileName2 = "E:\\FileWriteDemo\\src\\RevisedNumbers.txt";
File file2 = _getFile(locationWithFileName2);
FileWriter fileWriter2 = new FileWriter(file2);
// creating a temporary file
String tempFileLocationWithName = "E:\\FileWriteDemo\\src\\temporary.txt";
File tempFile = _getFile(tempFileLocationWithName);
FileWriter tempFileWriter = new FileWriter(tempFile);
Scanner scanner = new Scanner(file1);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
// split the word "Number" from integer
String words[] = currLine.split(" ");
for (int i = 0; i < words.length; i++) {
// System.out.println(words[i]);
try {
int num = Integer.parseInt(words[i]);
if (num >= 5 && num <= 7) {
// writing to second file
fileWriter2.write(currLine);
fileWriter2.append('\n');
} else {
// writing to temporary file
tempFileWriter.write(currLine);
tempFileWriter.append('\n');
}
} catch (NumberFormatException e) {
// current word is not an integer, so don't have to do anything
}
}
}
fileWriter2.close();
tempFileWriter.close();
_copyFromOneFileToAnother(tempFile, file1);
System.out.println("\nContents of first file");
_readFile(new Scanner(file1));
System.out.println("\nContents of second file");
_readFile(new Scanner(file2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope it helps!
Happy coding.
I have converted the db file into csv file and worked perfectly in android. But I manually deleted the csv file from storage location and try to run the same code. but I am unable to write the file into the same location. No exception noticed.
The code used is as follows:
public void exportTopic() {
int rowCount, colCount;
int i, j;
Cursor c=null;
SQLHelper helperr=null;
try {
helperr=new SQLHelper(getActivity());
c = helperr.getAllTopics();
Log.d("exportPath", sdCardDir.getPath());
String filename = "MyBackUp.csv";
File CsvFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(CsvFile);
BufferedWriter bw = new BufferedWriter(fw);
rowCount = c.getCount();
colCount = c.getColumnCount();
if (rowCount > 0) {
c.moveToFirst();
for (i = 0; i < rowCount; i++) {
c.moveToPosition(i);
for (j = 0; j < colCount; j++) {
if (j != colCount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
}
} catch (Exception ex) {
Log.d("Exception","at export topic");
helperr.close();
ex.printStackTrace();
}
helperr.close();
c.close();
}
I am calling the function from here:
private View.OnClickListener clickHandler = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.exportToDropBtn) {
try {
exportTopic();
}catch (Exception e){
Log.d("Exception","at export button");
e.printStackTrace();
}
}
Add code to create a file if it does not exist:
File dir = new File(Environment.getExternalStorageDirectory() + "/yourAppName");
// make them in case they're not there
dir.mkdirs();
File wbfile = new File(dir, fileName);
try {
if (!wbfile.exists()) {
wbfile.createNewFile();
}
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(
new FileWriter(wbfile, true));
buf.append(strBuilder.toString());
buf.newLine();
buf.close();
} catch(Exception e){
e.printStackTrace();
}
I have a for loop that runs 20.000 times with a for loop inside it that runs 20.000 times as well which adds up to a total of 400 million.
in the for loop it adds 20.000 numbers to a string and then writes this string into a txt file. after the writing the string is being set empty like this :String Name = "";
so i will get a total of 20.000 text files with each 20.000 numbers in it.
now if the for loop has created about 200 files it starts to run out of memory and crashes eventually.
how can i avoid this?
-- here is the code --
public static void mapScanner()
{
String content = "";
for(int z = -10000; z < 10000; z++)
{
Util.CreateFile(z);
for(int x = -10000; x < 10000; x++)
{
Block block = Bukkit.getServer().getWorld("world").getBlockAt(x, Bukkit.getServer().getWorld("world").getHighestBlockYAt(x, z) -1, z);
if(block.getType() != Material.AIR)
{
content += Blocks.blockID(block.getType());
}
}
try
{
File file = new File("plugins/Map/" + z + ".txt");
System.out.println(content);
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
content = "";
System.out.println("The file : " + z + ".txt has been created and written.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
block.getType() just returns a number.
General code :
for(int x = 0; x < 20000; x++)
{
String content = "";
CreateFile(x);
for(int z = 0; z < 20000; z++)
{
content += "1";
}
try
{
File file = new File("Map/" + x + ".txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
//System.out.println("The file : " + x + ".txt has been created and written.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void CreateFile(int z) {
File file = new File("Map/" + z + ".txt");
boolean fileCreated = false;
try {
fileCreated = file.createNewFile();
} catch (IOException ioe) {
//System.out.println("Error while creating empty file: " + ioe);
}
if (fileCreated) {
//System.out.println("Created empty file: " + file.getPath());
} else {
//System.out.println("Failed to create empty file: " + file.getPath());
}
}
You will always have performance problems if you keep all contents in memory, show me some code to help you.
One way to me to do this, it's write directly to the file so no need to keep the string in memory.
Sorry for my grammar anyway, I'm not great at writing...
Try something like this instead:
public static void mapScanner()
{
String content = "";
for(int z = -10000; z < 10000; z++)
{
File file = new File("plugins/Map/" + z + ".txt");
// if file doesn't exists, then create it, this inside another try.
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fw = new FileOutputStream(file);
OutputStream bw = new BufferedOutputStream(fw);
for(int x = -10000; x < 10000; x++)
{
Block block = Bukkit.getServer().getWorld("world").getBlockAt(x, Bukkit.getServer().getWorld("world").getHighestBlockYAt(x, z) -1, z);
if(block.getType() != Material.AIR)
{
string temp = Blocks.blockID(block.getType());
System.out.println(temp);
bw.write(temp.getBytes());
}
}
try
{
// Close all
bw.flush();
bw.close();
fw.close();
file.close();
System.out.println("The file : " + z + ".txt has been created and written.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
replace String content = "" with StringBuilder content = new StringBuilder() and content += Blocks.blockID(block.getType()) with content.append(Blocks.blockID(block.getType()))
this should make your loop run quite a lot faster. i doubt it will help with your OutOfMemory problem, though.
I have a dialog using JFileChooser. When I save a file by FileOutputStream, I want to save it as file.txt in the path which the user want. But it always saves in c:/user/Document.
Here is the code:
DownLoadDialog downloadDialog = new DownLoadDialog();
int result = downloadDialog.showSaveDialog(queryPanel);
if (result == downloadDialog.APPROVE_OPTION) {
File file = downloadDialog.getSelectedFile();
//String parth =file.getPath();
//System.out.println(parth);
//if(file.exists()) {
//int response = JOptionPane.showConfirmDialog (null,
// "Overwrite existing file?","Confirm Overwrite",
// JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
//if(response == JOptionPane.OK_OPTION) {}
//} else {
if (resultGoogleSearch > 0) {
{
String parth = new File(downloadDialog.getSelectedFile().
getAbsolutePath().concat(".txt")).toString();
System.out.println(parth);
for (int i = 0; i < resultGoogleSearch; i++) {
String[] temp = googleSearchResult.get(i).split("<br>");
//String resultURL = temp[0];
//File dir = downloadDialog.getCurrentDirectory();
try {
FileOutputStream googleReuslt = new FileOutputStream(
downloadDialog.getSelectedFile().getAbsolutePath()
+ ".txt");
OutputStreamWriter writer = new
OutputStreamWriter(googleReuslt);
BufferedWriter buffer = new BufferedWriter(writer);
writer.write(temp[0]);
writer.close();
buffer.close();
} catch (FileNotFoundException fEx) {
} catch (IOException ioEx) {
}
}
}
JOptionPane.showMessageDialog(IDRSApplication.idrsJFrame,
IDRSResourceBundle.res.getString("successful"));
}
The problem is here: why can't I set path for new file?
FileOutputStream googleReuslt = new FileOutputStream(
downloadDialog.getSelectedFile().getAbsolutePath() + ".txt");
OutputStreamWriter writer = new OutputStreamWriter(googleReuslt);
BufferedWriter buffer = new BufferedWriter(writer);
writer.write(temp[0]);
writer.close();
buffer.close();
The code you provided works as you would expect. (At least under linux.)
I suggest you do a SSCCE and update your question.