Menu
  • HOME
  • TAGS

how to save information from a file in java

java,string,file,io

To read files I recommend to you to use an ArrayList: Scanner s = new Scanner(new File(//Here the path of your file)); ArrayList<String> list = new ArrayList<String>(); while (s.hasNext()) { list.add(s.nextLine()); } Now in your ArrayList you will have all the lines of your file. So, now, you can go...

Apache POI is extremely slow

java,excel,io,apache-poi

It turns out to be a network problem. The connection speed to the drive where the excel file is located is slow.

Why I am getting shifted output when write to a text after converting it to xls file in java [closed]

java,excel,csv,io,html-parsing

It's a very good bet that writing CSV files will fix this since it appears the problem is Excel guessing how to put your text data into columns. Note that CSV is not a standard. CSV formats vary between different programs, e.g. how to do quoting and whether newlines can...

Pylint on StringIO or buffered text

python,io,pylint

I am afraid it's impossible to run analize on a code-string. The pylint docs say: pylint [options] module_or_package Also, epylint.py: def py_run(command_options='', return_std=False, stdout=None, stderr=None, script='epylint'): """Run pylint from python ``command_options`` is a string containing ``pylint`` command line options; ``return_std`` (boolean) indicates return of created standard output and error (see...

FileNotFoundException While trying to copy the file from one directory to another

c#,.net,io,filenotfoundexception

You're trying to move the entire directories with File.Move. You have to specify the file name as well: File.Move(file, Path.Combine(dp, Path.GetFileName(file))); ...

In ubuntu unable to write file in specified directory using java

java,ubuntu,io

You cannot write outside of the /home/ directory by default. Also sudo is a command, you cannot execute a command from a BufferedWriter. So, launch your jar with sudo java -jar yourJar.jar or launch your IDE in root (for eclipse sudo eclipse). And try something like that: import java.io.BufferedReader; import...

Why does grep give “Binary file (standard input) matches”?

c,file,api,io,pipe

You are attempting to write 36 bytes instead of 6, effectively accessing bytes beyond the end of the string. Definitely undefined behaviour. Only the first '\0' byte is expected. Use fwrite("Hello\n", 1, 6, cmd); Or more simply: fputs("Hello\n", cmd); ...

Reading unformatted name/value pairs from a file, formatting it, and printing it out in Python 2 dictionary [closed]

python,python-2.7,dictionary,io

This will ignore any lines without a '=', then from the remaining lines, remove any quotes and whitespace on the outside of each key and value, then put it into a dict: data = {} with open('in.txt', 'r') as fh: for line in fh: if '=' not in line: continue...

unreported exception filenotfoundexception [closed]

java,io

you're using the read method: note that this method can also throw an IOException. See the docs for the read method here, the declaration is: public final int read(byte[] b) throws IOException So you'll also need to catch IOException, or report that your method throws IOException. Note that you don't...

Issue reading and saving lines from .txt file in Java

java,arraylist,io

You are not reading the file at all in your extractTextFile() method. Files.write() is for writing the contents of the Arraylist to the file. You may want to use Files.readAllLines(path);...

Output EOF using %f

c,io,printf,eof,format-specifiers

Using a wrong format specifier for any particular argument in printf() invokes undefined behaviour. EOF is of type int. You can only use %d for an int type variable. FWIW, if you want a floating point representation of an int, you have to cast the variable (but I personally recommend...

why char* why not bool* can be used in write function in c++ file I/O

c++,file,io,typecasting-operator

In this statement why cast x to char* and not to bool* ... It suspect you are thinking that a bool, conceptually a single bit, is the most basic data type in C++. That is not the case. Individual bits are not addressable in C++. The C++ memory model...

Take C++ program output as Java input

java,c++,linux,io

Looks like you have all the Java and C++ code already in place. The missing puzzle piece seems to be the shell redirection. You should consult the manual of the shell you are using and look for redirection. In case you are using bash shell the redirection should look like...

Using pygame to play a MIDI file from stream

python,io,pygame,midi,bytesio

I fixed the issue as follows: bytestream = io.BytesIO() midi.writeFile(bytestream) temp = io.BytesIO(bytestream.getvalue()) pygame.mixer.music.load(temp) As it seems, the writeFile() operation somehow makes the BytesIO object invalid to the pygame.mixer.music.load() method. By using the constructor of BytesIO again with the correctly created bytestream we magically get a valid bytestream we can...

In the dart:io library, why would one want to set runInShell: true when calling Process.run?

shell,process,io,dart

You can just create a new child process with your_executable or alternatively with runInShell, create a new child process with the shell executable and pass -c your_executable to make the shell create a new child process with your_executable. For example if you want to execute bash builtins or if you...

ResourceNotFoundException on existing path

java,io,velocity,resource-loading

Instead of using the full absolute path, load it from classpath, because it is already in classes folder. subjectTemplate = Velocity.getTemplate("velocityTemplates/terminalModerationStatusChanged.vm", "UTF-8"); ...

Convert InputStream into Stream given a Charset

java,io,stream,java-8,java-stream

I think you can try: Stream<String> lines = new BufferedReader(new InputStreamReader(is, cs)).lines(); ...

select() function for simultaneously I/O

python,multithreading,sockets,select,io

Though select() will work, you have to use threads if you want to do other things while the system is blocked on the select. Have a look at glib's GIO library. There you can connect callbacks to the actions you want to monitor or act on, for example the 'connect's...

How would I go about searching for a string of words across multiple lines

java,parsing,input,io,bufferedreader

I think that either you: Normalize your key phrases and names (represent "word\nplus\nword" as "line n has word, line n+1 has plus, line n+2 has word") Process newlines as part of the matching characters (process byte by byte instead of line by line) From your current strategy, option 1 would...

Modern C++ idiom for allocating / deallocating an I/O buffer

c++,memory-management,io

Basically, you have two main C++-way choices: std::vector std::unique_ptr I'd prefer the second, since you don't need all the automatic resizing stuff in std::vector, and you don't need a container - you need just a buffer. std::unique_ptr has a specialization for dynamic arrays: std::unique_ptr<int[]> will call delete [] in it's...

Firefox OS - save file in the app directory

javascript,audio,io,firefox-os,howler.js

Any file that is packaged in the app can be accessed using a relative url. Which means you don't have to get a blob or anything. It won't be possible to save assets (at runtime) in the app folder as far as I can tell. The only way to...

Are fputwc and fgetwc significantly faster than fprintf and fscanf? Why is it so?

c,performance,io,wchar-t

I did some quick profiling using only a single wchar_t per call, and there is indeed a noticable difference. First, the code: #include "stdio.h" #include "time.h" #include "wchar.h" wchar_t text[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$"; const int N = 64; const int M = 500000; int main() { int i, j; FILE *f1...

Clone a file and modify it

c#,file,io

The problem is that you're opening the output file on every iteration. Instead, you should have both files open at the same time: using (var reader = File.OpenText(@"c:\test.txt")) { using (var writer = File.CreateText(@"c:\test2.txt")) { string line; while ((line = reader.ReadLine()) != null) { // Handle triggers or whatever writer.WriteLine(line);...

C - does read() add a '\0'?

c,unix,io,posix,unbuffered

does read() add a '\0'? No, it doesn't. It just reads. From read()'s documentation: The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf. Is there potential for error here, other than the...

monitor log4j behaviour under load

logging,concurrency,io,log4j

As nobody answered my question, This link somehow help me through solving my problem. Log4j writes to files and the console serially. so while one thread is writing another thread that wants to write has to wait until the other one is finished. also, stdout can block if whatever is...

How do I do user inputs on the same line in Lua?

input,io,lua

When called without arguments, io.read() reads a whole line. You could read the line and get the words using pattern matching: input = io.read() opr, txt = input:match("(%S+)%s+(%S+)") The above code assumes that there is just one word for opr and one word for txt. If there might be zero...

How does C distinguish between a byte long character and a 2 byte long character?

c,linux,bash,io,kernel

C doesn't interpret it. Your program reads 2 bytes and outputs same 2 bytes without caring about what characters (or anything else) they are. Your terminal encodes your input and reinterprets your output back as the same two byte character....

how to reattach sys.stdout to console window in python?

python,io,stdout,stringio,redirectstandardoutput

You're looking for sys.__stdout__: It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved...

How can I redirect, in Go, the stdout and stderr of a command to both the console and a log file while outputting in real time?

go,io,sync

As I said in the comment section, this can be achieved using MultiWriter package main import ( "io" "log" "os" "os/exec" ) func main() { // Logging capability f, err := os.OpenFile("log.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening file: %v", err) } defer f.Close() mwriter := io.MultiWriter(f,...

Unique words save to text file as a word per line

python,file,python-3.x,io,text-files

unique = str(unique) + i + " " + str(newWords.count(i)) + "\n" The line above, is appending at the end of the existing set - "unique", if you use some other variable name instead, like "var", that should return correctly. def uniqueFrequency(newWords): '''Function returns a list of unique words with...

Parsing text file lines into numbers using std::iter::Iterator map

file,text,io,rust

Let's look at the complete error message, which points to the error for us: <anon>:5:9: 5:14 error: mismatched types: expected `&core::result::Result<&str, ()>`, found `core::result::Result<_, _>` (expected &-ptr, found enum `core::result::Result`) [E0308] <anon>:5 Ok(s) => match s.parse() { ^~~~~ The compiler is expecting a &Result, but found a Result, and the...

How to make an array loaded from netCDF (.nc) writeable?

python,arrays,numpy,io,netcdf

From the docs http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.io.netcdf.netcdf_file.html NetCDF files, when opened read-only, return arrays that refer directly to memory-mapped data on disk: >>> >>> data = time[:] >>> data.base.base <mmap.mmap object at 0x7fe753763180> If the data is to be processed after the file is closed, it needs to be copied to main memory:...

Mixing Java NIO with IO input streams read operation

java,sockets,io,nio

No. You can only use streams on the channel socket if the channel is in blocking mode, in which case you wouldn't have a SelectionKey.

Python subprocess input is read twice

python,io,subprocess,stdin

The bug is actually in your C++ program; it re-uses the in variable for both of its prints, which means if the second call to getline doesn't return anything (and it doesn't in your case, because the EOF of stdin is reached after the first getline call), the contents returned...

How to grep a string in a program?

c,linux,io,grep,pipe

Use popen: FILE* file = popen( "grep mykeyword", "r" ); fwrite( str_to_grep, 1, strlen( str_to_grep ), file ); pclose( file ); The echo example by Matt might not work as expected if the string has quotes or similar character interpreted specially by the shell. I assume your example with grep...

how to write the output of iostream to buffer, python3

python,string,io,stream,wrapper

You use open() to open the file, so it isn't a StringIO object, but a file-like object. To get the contents of the file after you write to it you can open the file with mode = 'w+', and instead of fd.getvalue(), do: fd.seek(0) var = fd.read() This will put...

ERROR ITMS-90092: “This bundle is invalid…" [duplicate]

xcode,io,armv7,submission

I finally figured out how to bypass this error and successfully submit my app. Here is what you have to do if you already have armv7 included under build settings > valid architectures: Run the app on your phone with the usb cord pugged into the computer. Once the app...

the use of fflush(FILE* stream)

c,io,fflush

The best way to know what it does is the standard 7.21.5.2 The fflush function Synopsis #include <stdio.h> int fflush(FILE *stream); Description If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for...

Is there a simple way to tell if a StackTraceElement is not from your source code?

java,io

extracting from comments(duffymo's and mine) Pick a unique top-level package name. Example will be com.yourcompany or com.productname... etc In the exception handling routine, check if the package starts with your pattern. ...

Appending lines for existing file in python [duplicate]

python,file,python-2.7,io

The issue is in the code - curr_file = open('myfile',w) curr_file.write('hello world') curr_file.close() The second argument should be a string, which indicates the mode in which the file should be openned, you should use a which indicates append . curr_file = open('myfile','a') curr_file.write('hello world') curr_file.close() w mode indicates write ,...

How to prevent a race condition when multiple processes attempt to write to and then read from a file at the same time

python,io,race-condition,python-import,python-os

The way to do this is to take an exclusive lock each time you open it. The writer holds the lock while writing data, while the reader blocks until the writer releases the lock with the fdclose call. This will of course fail if the file has been partially written...

How to read, filter and modify lines from a file

filter,io,rust

Here you go: use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let f = BufReader::new(File::open("/etc/passwd").unwrap()); let it = f.lines() .map(|line| line.unwrap()) .filter(|line| line.ends_with("/bin/bash")) .map(|line| line.split(":").next().unwrap().to_owned()); for p in it { println!("{}", p); } } This code allocates a separate string for each first splitted part though, but I don't think...

How to find condition that start char in UTF-8 file is read, using FileStream and StreamReader?

c#-4.0,utf-8,io,stream

bool first = true; while((i = reader.Read()) > -1) { if (first) { first = false; // Do first character things } Note that the concept of first character is complex: what happens if the first glyph is è, that occupies two bytes in the file? The stream position will...

Mapping with IO actions in Haskell

list,haskell,io

Here is a function f' which does what you describe. f' :: [(String,String)] -> IO [Bool] f' = mapM $ uncurry f Let me know if something is unclear! And, just to be clear, here is how you run it: main = do res <- f' [("a.txt", "b.txt"), ("c.txt", "d.txt")]...

Custom streambuffer in std::ofstream

c++,io,streambuf

The concrete file stream classes have their own rdbuf() method that takes 0 arguments and it hides the other rdbuf() method inherited from the virtual base std::basic_ios. Qualifying the name to lookup the base class method should work: std::ofstream ofs; ofs.basic_ios<char>::rdbuf(example.rdbuf()); ...

C# Linq Dictionary IO

c#,linq,dictionary,io,statistics

I'd suggest to create custom class which can hold/store related data. Let it be Statisztika with the following fields/properties: Day, PersonId, Visitor and CountOfVisits. Statisztika class definition: public class Statisztika { private int iday = 0; private int ipersonid = 0; private int ivisitor =0; private int icount =0; //class...

function to delete folders older than 10 days in vb

vb.net,io

Iterate through the directory, get each folder's properties, and get the TimeSpan difference from today to the folder's creation date. Try Dim dtCreated As DateTime Dim dtToday As DateTime = Today.Date Dim diObj As DirectoryInfo Dim ts As TimeSpan Dim lstDirsToDelete As New List(Of String) For Each sSubDir As String...

java.nio.charset.MalformedInputException: Input length = 1

java,io,character-encoding,malformed

You can try to utilize the correct encoding by using the Files.lines(Path path, Charset charset) form of the lines method (javadocs). Here's a list of supported encodings (for the Oracle JVM anyhow). This post indicates that "Cp1252" is Windows ANSI....

javscript readstream line by line

javascript,file,csv,io

Should be easier if you go easier ... var fs = require('fs'), readline = require('readline'); var rd = readline.createInterface({ input: fs.createReadStream('Domain.csv'), output: process.stdout, terminal: false }); rd.on('line', function(line) { console.log(line); }); ...

Why is my text file always empty?

java,file,io

DataOutputStream.writeInt does not write an integer as text; it writes a "raw" or "binary" integer consisting of 4 bytes. If you try to interpret them as text (such as by viewing them in a text editor), you get garbage, because they're not text. For example, if your score is 100,...

Faulty file in use error

c#,winforms,io

You should seperate your reading logic from your update logic. for example: var replacements = dir.GetFiles() .Where(file => animals.Any(animal => file.Name.StartsWith(animal))) .Select(file => new { OldFullName = file.FullName, NewFullName = file.FullName.Replace(file.Name, "Animals-" + file.Name) }) .ToList(); foreach (var replacement in replacements) { File.Move(replacement.OldFullName, replacement.NewFullName); } Your replace logic has some...

2- vs 3-argument open with '-'

perl,io,stdin

perldoc -f open: In the two-argument (and one-argument) form, opening <- or - opens STDIN and opening >- opens STDOUT. I think this makes it clear that the special treatment of - is specific to the one- or two-argument forms. You could just assign \*STDIN to your $in, or open...

IO reading (java)

java,io

Yes it will "will it put one word in array[i] and the next word in array[i+1]". Note that nextToken() returns the next token from st string tokenizer. Be careful about the NoSuchElementException - if there are no more tokens in st tokenizer's string. Try something like this: while(st.hasMoreTokens() ) {...

writing and reading a txt content using java

java,io,bufferedreader

To append to existing file use FileWriter with append = true argument in constructor: FileWriter fileWriter= new FileWriter(fileName,true); BufferedWriter bufferWriter = new BufferedWriter(fileWriter); bufferWriter.write(inputString); bufferWriter.close(); Read more about FileWriter here...

Getting input java

java,io

The issue is that after reading a float from the scanner, a newline "\n" is left in the scanner, this means that when the first scan.nextLine() runs, it gets that leftover newline, which results in your code hitting the else block, and breaking out of the loop. You can either...

User Input Java

java,input,io

From the documentation of System#console, it returns: The system console, if any, otherwise null. So your code is equivalent to: String firstName = null.readLine("What is your name? "); I would suggest you to use Scanner scanner = new Scanner(System.in); instead....

How to improve the performance of Haskell IO?

haskell,io

Your example is slow because it uses lazy IO with String-s. Both have their own overheads. In particular, String is a linked list of Char-s, therefore it has two words of space overhead for each character (one word for the constructor tag and one for the forward pointer), and each...

the logic behind the diffrerence between fileInputStream and Scanner classes

java,io,java.util.scanner,fileinputstream

Files contain bytes. FileInputStream reads these bytes. So if a file contains one byte whose value is 49, stream.read() will return 49. If the file contains two identical bytes 49, calling read() twice will return 49, then 49. Characters like 'a', '1' or 'Z' can be stored in files. To...

How to call Fortran routine with unit number argument from C

c,io,fortran,shared-libraries,abi

This is completely compiler dependent, there is no portable correspondence. See the manual of your compiler if they support some sort of interoperability as an extension.

perl: canot open file within a loop

perl,io

You have newlines at the end of each filename: my @olap_f = `ls ~dir_to_file/*txt`; chomp @olap_f; # Remove newlines Better yet, use glob to avoid launching a new process (and having to trim newlines): my @olap_f = glob "~dir_to_file/*txt"; Also, use $! to find out why a file couldn't be...

Haskell: Clear file contents using an open handle

haskell,io,handle

You can use hSetFileSize to truncate a file to a given size.

Fortran runtime error “bad integer for item 11 in list input”

io,fortran

Item 11 in your list is 0.09587, a real. You are using list directed input, which for a real is interpreted a numeric value using an F edit descriptor (Fortran 2008 Cl. 10.10.3 paragraph 4). An input list item corresponding to an F edit descriptor must be real or complex...

read in file in python

python,file,io,readfile

The last line of your read(s) will not return \n but an empty string, to indicate that the file was read completely. Why not use something like with open("testdata.txt") as infile: lines = infile.readlines() block = "" for line in lines: if line.strip() == "": break block += line you...

Java 7 - Stream data through class hierarchy

java,performance,io,stream

You essentially want to implement the Pipeline Pattern. If you're passing byte data, you've got a ready made implementation with the InputStream/OutputStream classes (where you'd extend FilterInputStream and FilterOutputStream). If you intend to pass objects, I recommend creating your own "object stream" classes (don't use ObjectInputStream/ObjectOutputStream, they're for serialization)....

read() : Invalid arguments

c,io

You should only check errno if read returns -1 to indicate that it got an error. int n; if ((n = read(input, buffer_header, 4)) > 0) { image_width = bytesToInt(buffer_header); } else if (n == -1) { perror("read"); } else { printf("EOF\n"); } ...

Unidentified symbol

java,io,symbol

Make the changes as below: while ((characterInt = fr.read()) != -1) { //characterInt = fr.read(); str += "" + (char) characterInt; } Read the char and compare it with -1 as EOF. You were appending the end of file char in string and then while loop condition was getting failed....

Maximum size/offset of streamed File using Ada.Streams.Stream_IO.Read

io,filestream,ada,gnat

On Mac OS X, with FSF GCC 5.1.0, there is procedure Read (File : File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset; From : Positive_Count); where type Count is new Stream_Element_Offset range 0 .. Stream_Element_Offset’Last; subtype Positive_Count is Count range 1 .. Count’Last; --' -- Index into file, in...

Trying to use output of one function to influence the next function to count words in text file

python,file,python-3.x,io,count

The problem is quite simple: You split it into two function, but you completely ignore the result of the first function and instead calculate the number of words before the cleanup! Change your main function to this, then it should work. def main(): harper = readFile("Harper's Speech.txt") newWords = cleanUpWords(harper)...

Reading a file in C and passing the contents to main()

c,arrays,file,io

Sometimes, there is good reason to be able to simply call a function to read a file and have the function return a pointer to an allocated array of strings holding the file's contents. This is especially true when you have no idea how long the file is. While you...

Why is it slower to print directly to console/terminal than redirecting?

linux,io,terminal

Primarily, terminals are just plain slow. For every update, they have to: Parse and interpret any control codes. Parse, interpret and render any escape codes. Interpret and account for any multibyte and composed characters. Update appropriate screen and scroll buffers. Render this with appropriate fonts. and possibly do all of...

C++ not reading anything from files

c++,io

Change the lines: if (inStream.bad()) { inStream.close(); outStream.open(filename); outStream << "This is a test file: \nWelcome to the Dark Side!"; outStream.close(); } inStream.open(filename, ios::in); if (inStream.good()) to if (inStream.bad()) { inStream.close(); outStream.open(filename); outStream << "This is a test file: \nWelcome to the Dark Side!"; outStream.close(); // Clear the state of...

how to read in files made of double values line by line using c++

c++,io

use getline and stringstream while(getline(file,str)){ stringstream stream(str); double something; while(stream>>something){ //Push it into inner vector<double> } //push vector<double> into vector<vector<double> > here } You can work out the inner details yourself....

ruby: running a command from a forked child process

python,ruby,ssh,io,fabric

Turned out being a matter of redirecting stdin from parent to child process. See below: Perl's backticks/system giving "tcsetattr: Input/output error" Access STDIN of child process without capturing STDOUT or STDERR This is the solution: read_io, write_io = IO.pipe job1 = fork do write_io.close STDIN.reopen(read_io) puts `fab example` end Process.detach(job1)...

Can't write to a Handle

haskell,io,handle

When you write to a file, the OS keeps track of the position at which you are in said file. You get an EOF error because you're at the end of the file (it was empty to begin with and everything you have written is before the current position). To...

read file from assets android

android,io

StringBuffer stringBuffer = new StringBuffer(); try { InputStream is = mContext.getResources().getAssets().open("your-file-path"); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = br.readLine()) != null) { //play with each line here } }... Try this code to get data from the assets. OR if you don't want to...

Can someone explain mdict in python (scipy.io), for example in scipy.io.savemat()?

python,matlab,io,scipy

According to the docs, savemat is defined as io.savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as='row') So the 2nd argument is required, and may be provided with or without the mdict=... part. The reason why it expects this to be a dictionary is that it needs to know the name(s) under...

Loading resource files within a jar

java,jar,io,loading

This snippet of code worked for me: Clip clip = null; ClassLoader cl = this.getClass().getClassLoader(); AudioInputStream ais; URL url = cl.getResource("com/example/project/assets/TestSound.wav"); System.out.println(url); try { ais = AudioSystem.getAudioInputStream(url); clip = AudioSystem.getClip(); clip.open(ais); } catch (Exception e) { e.printStackTrace(); System.exit(1); } The important thing is not adding the /src/ folder to the...

Python csv seek() not working

python,csv,io

Use the csv module. import csv n = 3 m = 5 read = 0 with open("so.csv") as csvfile: reader = csv.reader(csvfile) for record in reader: read += 1 if read >= n and read <= m: print(record) ...

how to effectively write text file in C and the size of file would be 5GB

c,io

I have tested a null implementation of your code to see what is fwrite performance and I believe the bottleneck definitely isn't fwrite. #include <stdio.h> #include <string.h> char *icmDisassemble(int x, int y) { return "The rain in Spain falls mostly on the plain"; // return "D'oh"; // return "Quel ramo...

input errors : split part of one entery

c++,input,io

You have to check for the '+' and the trailing 'i': istream &operator>>(istream &input, Complex &complex) { char plus,letter; if (input >> complex.realPart >> plus) { if (plus!='+' ) input.setstate(ios::failbit); else if (input >> complex.imaginaryPart>>letter) { if (letter!='i') input.setstate(ios::failbit); } } return input; } Live demo here Note that you...

Golang file reading only reading last line

csv,go,io,file-read

The basic problem is that this file has \r line endings. It also isn't valid UTF-8. Together, those are going to cause Scanner a lot of trouble. First, we can see exactly what's in the file using xxd 00000000: 2c2c 2c25 206f 6620 546f 7461 6c20 4578 ,,,% of Total...

In Yesod/Haskell, how do I use data from IO with the variable interpolation functionality?

haskell,io,monads,yesod

When working with monad transformers, to convert from some monad m to a transformer t m, you have to use the lift function: lift :: (MonadTrans t, Monad m) => m a -> t m a This is actually the defining method of the MonadTrans typeclass, so the implementation is...

How fast can we make a specific tr?

c,performance,io

Combining ideas from the various answers with some extra bithacks, here is an optimized version: #include <errno.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define BUFFER_SIZE 16384 #define REPLACE_CHAR '@' int main(void) { /* define buffer as uint64_t to force alignment */ /* make it one slot longer to...

How to get the screen shot of the window on mac?

io

use Command + shift + 4, and you will get a crosshair. After you have outlines what is in the screenshot, press the space bar to capture. Hope this helps.

File I/O error FileNotFoundException

java,io,backtracking

ProjectRoot is working directory for Eclipse. Move file above src directory i.e. to project root (Running from eclipse) openFile = new File("problem1.txt"); Provide path from src or bin to file location (Running from eclipse): openFile = new File("src/superbase/problem1.txt"); ...

Find and append to file without loading it in memory?

c#,.net,file,io,stream

The solution for me in this case was XML Inclusion Technique, it is not perfect but the login is much simplier. I can use appendToFile instead of manipulate or read into memory.

Using allocatable/assumed-size arrays with namelist read write

io,fortran,intel-fortran,fortran2003

That looks like a compiler bug. The array grid is assumed shape, not assumed size. Assumed shape arrays are permitted in namelist as of F2003, assumed size arrays remain prohibited (at runtime the size of an assumed size array is not necessarily known, so operations that require knowledge of the...

How do I implement a timeout when using File.Copy?

c#,.net,file-io,io,timeout

For example, it can be done this way using async-await pattern: Task timeoutTask = Task.Delay(TimeSpan.FromSeconds(10)); // I use a completion source to set File.Copy thread from its own // thread, and use it later to abort it if needed TaskCompletionSource<Thread> copyThreadCompletionSource = new TaskCompletionSource<Thread>(); // This will await while any...

Directory not empty java.io.IOException

java,osx,io,external,runtime.exec

As I'd suspected, there was a problem with runtime itself! There's one more JavaFX app that acts as installer for this app (app with Runtime problems). For installation of this app I had used following code to copy contents of .app file: public static final void copyFile( File source, File...

Rust: Lifetime of String from file [duplicate]

file,io,rust

The string bound to "s" will be deallocated once the function ends ("s" goes out of scope), so you cannot return a reference to its contents outside the function. The best way is to return the string itself: fn read_shader_code(string_path: &str) -> String { let path = Path::new(string_path); let display...

Sequential file IO from different threads fail with FileSystemException

java,multithreading,windows-7,io

You simply had some typo in your FileMover run method: Path destination = origin.resolve(origin.getFileName().toString().replace(".in", ".out")); The destination will be like C:\temp\file_0.in\file_0.out this won't work, because it is a file and not a directory :-) Replace it something like that: String now = origin.toString().replace(".in", ".out"); Path destination = Paths.get(now); ...

How to read a middle size-specified chunk of a file in Python

python,io

The behavior I'm assuming would be to seek 5 MBs into the file and split the next 5 MBs into lines. You'd want something like: f.seek(5*1024*1024) lines = f.read(5*1024*1024).splitlines() Or manual counting (recommended method, much more efficient): f.seek(5*1024*1024) lines = [] while f.tell() < 10*1024*1024: line = f.readline(10*1024*1024-f.tell()) lines.append(line) However,...

C++ reading a file into a struct

c++,struct,io,fstream

This happens because the >> operator for the input stream only grabs part of a line, and does not always grab the newline character at the end of the line. When followed by a call to getline, the getline will grab the rest of the line previously parsed, not the...

Python will Sometimes Not Read in Entire File

python,io,enumeration

On further reflection I realized it was because I had created the file earlier in the program and had not closed the file handle, and this was therefore perhaps a buffering issue. Closing the file earlier fixed the problem. It was suggested that I use "with" syntax for writing to...

OutputStream class is used for writing into files. How is it possible?

java,io,outputstream

Just because the declared type is OutputStream, that doesn't mean the implementation doesn't create an instance of a concrete subclass of OutputStream. You see this all the time with interfaces. For example: public List<String> getList() { return new ArrayList<String>(); } Basically you need to distinguish between the API exposed (which...

where is the text printed by C printf

io,common-lisp,cffi

The problem is that C's stdio library has its own buffering that has nothing to do with Lisp's. Flushing the output requires you to have a pointer to C's FILE *stdout variable. You can get this pointer like this: (cffi:defcvar ("stdout" stdout) :pointer) Then, after using printf: (cffi:foreign-funcall "fflush" :pointer...

Storing columns on disk and reading rows

c++,file,matrix,io

Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...

Creating objects with data from file

java,file,io,hashmap

It ultimately comes to what you want to do with the data. If you want to create an instance of a class that stores the data for each entry in the file, the current parsing is probably fine. You can do it with key-value pairs like a hash map (or...